When are bisect_left and bisect_right not equal?

bisect.bisect_left returns the leftmost place in the sorted list to insert the given element. bisect.bisect_right returns the rightmost place in the sorted list to insert the given element.

An alternative question is when are they equivalent? By answering this, the answer to your question becomes clear.

They are equivalent when the the element to be inserted is not present in the list. Hence, they are not equivalent when the element to be inserted is in the list.


To me this interpretation of bisect_left/bisect_right makes it more clear:

  • bisect_left returns the largest index to insert the element w.r.t. <
  • bisect_right returns the largest index to insert the element w.r.t. <=

For instance, if your data is [0, 0, 0] and you query for 0:

  • bisect_left returns index 0, because that's the largest possible insert index where the inserted element is truly smaller.
  • bisect_right returns index 3, because with "smaller or equal" the search advances through identical elements.

This behavior can be simplified to:

  • bisect_left would insert elements to the left of identical elements.
  • bisect_right would insert elements to the right of identical elements.

When the target to locate is in the list, bisect_left, bisect_right return different result.

For example:

>>> import bisect
>>> bisect.bisect_left([1,2,3], 2)
1
>>> bisect.bisect_right([1,2,3], 2)
2