Bisect a Python List and finding the Index

Nyxynyx picture Nyxynyx · Oct 4, 2013 · Viewed 15.8k times · Source

When I use the bisect_left() function, why do I not get the index of the element, but instead index + 1?

import bisect

t3 = ['carver', 'carvers', 'carves', 'carving', 'carvings']
print bisect.bisect(t3, 'carves')    # 3
print bisect.bisect(t3, 'carving')   # 4
print bisect.bisect(t3, 'carver')    # 1

Answer

Martijn Pieters picture Martijn Pieters · Oct 4, 2013

bisect.bisect() is a shorter name for bisect.bisect_right(), not bisect.bisect_left().

You'll need to use the full name, bisect.bisect_left(), instead:

>>> import bisect
>>> t3 = ['carver', 'carvers', 'carves', 'carving', 'carvings']
>>> bisect.bisect(t3, 'carves')
3
>>> bisect.bisect_left(t3, 'carves')
2
>>> bisect.bisect == bisect.bisect_right
True
>>> bisect.bisect == bisect.bisect_left
False