My new ebook “Comprehending Comprehensions” is on pre-sale and 40% off!

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.

I hope you learned something new! If you did, consider following the footsteps of the readers who bought me a slice of pizza 🍕. Your small contribution helps me produce this content for free and without spamming you with annoying ads.

References

Previous Post Next Post

Blog Comments powered by Disqus.