This short article shows how to use the module bisect from the Python standard library.

Are you familiar with the module bisect from the Python ๐Ÿ standard library?

It is a small module to help you work with sorted lists. If you have a sorted list and a new value, you can find the index where the new value would go by using the method bisect:

>>> value = 22
>>> ordered_values = [1, 5, 19, 23]
# `value` would go at index 3 -^

>>> import bisect
>>> bisect.bisect(ordered_values, value)
3  # the index where `value` would go

>>> ordered_values.insert(3, value)
>>> ordered_values
[1, 5, 19, 22, 23]

The function bisect tells you where a value would go... But if you want to insert it, bisect can also do that for you! Just use the method insort:

>>> ordered_values
[1, 5, 19, 22, 23]

# Let's add 21 in there, preserving the order:
>>> bisect.insort(ordered_values, 21)
>>> ordered_values
[1, 5, 19, 21, 22, 23]

The module bisect has four more methods: bisect_left, bisect_right, insort_left, and insort_right... The _left and _right tell you where to place ties (elements that are equal).

The methods bisect and insort, shown above, match their _right variants.

This article was generated automatically from this thread I published on Twitter @mathsppblog. Then it was edited lightly.

Come take a course!

The next cohort of the Intermediate Python Course starts soon.

Grab your spot now and learn the Python skills you've been missing!

References

Previous Post Next Post

Blog Comments powered by Disqus.