What is bisect.bisect_left() in Python?
In this Answer, we will learn about the bisect_left() method in Python. Let’s start by looking at when we need this method.
We may want to insert an element in a sorted list, but we may still want to maintain the sort order after insertion. If we do this operation over a long list, this will become a costly operation. In this situation, we can use the bisect module, which ensures that the list is automatically put in a sorted order.
The bisect_left() method is provided by the bisect module, which returns the left-most index to insert the given element, while maintaining the sorted order.
Syntax
The syntax of the bisect_left() function is given below:
import bisect
bisect.bisect_left(list, element, lo=0, hi=len(list), key=None)
list: This contains a list of sorted integers.element: This provides an element that needs to be inserted into the sorted list.lo(Optional): Default is 0. It defines the starting position within the list for the search.hi(Optional): Default islen(list). It defines the ending position within the list for the search.key(Optional): If thekeyparameter is None, the elements are compared directly without invoking any key function.
Code examples
Let’s look at an example to better understand this.
#import the moduleimport bisect#given sorted list of numbersnums = [1,3,5,7,10,25,49,55]#given element to be inserted into the listele = 26#get index where to insert the elementidx = bisect.bisect_left(nums, ele)#print the indexprint(f"Insert element {ele} at index {idx} in nums list to maintain sorted order.")
Code explanation
In the code snippet above:
- On line 2, we import the
bisectmodule, which contains methods likebisect_left,bisect_right, and so on. - On line 5, we declare and initialize the list
numsin a sorted order. - On line 8, we are given an element
eleto be inserted in the listnums. - On line 11, we pass
listandelementas parameters to thebisect_left()method, which returns an index. - On line 14, we print the returned index.
Let's see another code example for the bisect_left() method with hi and lo parameters.
#import the moduleimport bisect#given sorted list of numbersnums = [1,3,5,7,10,25,49,55]#given element to be inserted into the listele = 26#get index where to insert the elementidx = bisect.bisect_left(nums, ele, lo=4, hi=len(nums))#print the indexprint(f"Insert element {ele} at index {idx} in nums list to maintain sorted order.")
On line 11, the
bisect_left()function is used to find where the elementelecan be inserted into the sorted listnums, starting the search from index4(inclusive) and going up to the end of the list. The result is stored in the variableidx.
Let's explore another code example utilizing the bisect_left() method with the key parameter for advanced list manipulation.
import bisect# List of tuples representing letters and corresponding integersletters = [(1, "a"), (3, "b"), (5, "c"), (7, "d"), (10, "e"), (25, "f"), (49, "g"), (55, "h")]# Extract the first element of each tuple (the integer)lambdafun = lambda x: x[0]# Search for the index where the value 6 should be insertedidx = bisect.bisect(letters, 6, key=lambdafun)print(f"Insert element 6 at index {idx} in letters list to maintain sorted order.")
On line 7, the lambda is an anonymous function that takes one argument x and returns the first element (x[0]) of x. For example, in our case, if x is a tuple like (1, "a"), then x[0] would extract 1. This lambda function allows us to access the first element of each tuple when performing sorting on tuple elements.