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.

Become a better Python ๐Ÿ developer ๐Ÿš€

+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!

My book โ€œPydon'tsโ€ teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here ๐Ÿ๐Ÿš€.

References

Previous Post Next Post

Blog Comments powered by Disqus.