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
>>> 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]
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
>>> 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]
bisect has four more methods:
_right tell you where to place ties (elements that are equal).
insort, shown above, match their
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.
bisect, https://docs.python.org/3/library/bisect.html [last accessed 10-08-2022];