1

Can someone please explain me what the bisect_left function from the bisect library actually does? Example:

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

This code will print '1'. But what is the rule for this printing? Is '2' inserted in the list, because according to the Python documentation, it should "locate the insertion point for x(in this case 2) in the list to maintain sorted order". Please, maybe someone could provide more examples and could help me to understand! Thank you!

Ciprian
  • 33
  • 6
  • Did you read my post? Because I quoted the documentation in the post. Maybe some examples would help me. – Ciprian Feb 17 '21 at 20:08
  • 2
    Using `[1,2,3]` in your example might not be the best. You seem like you are confusing *indices* with *values* in the list. Use something like `bisect.bisect_left([10,20,30], 19)` to get a better understanding of what it returns. The function returns an index, not a value. The function itself doesn't do any insertion, but does tell you what `i` to use in something like `lst.insert(i,19)` – John Coleman Feb 17 '21 at 20:09
  • Yes, indices, i see. Thanks! – Ciprian Feb 17 '21 at 20:38

2 Answers2

9

Starting with bisect, one use (as shown here) is to find an index into one list that can be used to dereference a related list:

from bisect import bisect

def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
    i = bisect(breakpoints, score)
    return grades[i]

grades = [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
print(grades)

Output:

['F', 'A', 'C', 'C', 'B', 'A', 'A']

bisect_left operates the same way as bisect but in the case of a "tie" it will return the index to the "left" of the match (e.g., a score of 70 in the above example would map to "D" using bisect_left)

rhurwitz
  • 2,557
  • 2
  • 10
  • 18
2

Bisect maintains a list in sorted order. If you insert an item into the list, the list still maintains its order.

Since your list is already sorted, bisect.bisect_left([1,2,3], 2) will insert the item 2 after 2 in your list (since the item 2 is already present in list).

You can find more about the "bisect" module here:

https://docs.python.org/3/library/bisect.html

user1234
  • 257
  • 2
  • 13