pythonbisect

Python bisect_left


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!


Solution

  • 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)