Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator
bisect

What is bisect.bisect_left() in Python?

Gutha Vamsi Krishna

Overview

In this shot, 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

import bisect

bisect.bisect_left(list, element)

Parameters

  1. list: This contains a list of sorted integers.
  2. element: This provides an element that needs to be inserted into the sorted list.

Let’s look at an example to better understand this.

Code example

#import the module
import bisect

#given sorted list of numbers
nums = [1,3,5,7,10,25,49,55]

#given element to be inserted into the list
ele = 26

#get index where to insert the element
idx = bisect.bisect_left(nums, ele)

#print the index
print(f"Insert element {ele} at index {idx} in nums list to maintain sorted order.")

Code explanation

In the code snippet above:

  • In line 2, we import the bisect module, which contains methods like bisect_left, bisect_right, and so on.
  • In line 5, we declare and initialize the list nums in a sorted order.
  • In line 8, we are given an element ele to be inserted in the list nums.
  • In line 11, we pass list and element as parameters to the bisect_left() method, which returns an index.
  • In line 14, we print the returned index.

RELATED TAGS

python
communitycreator
bisect
RELATED COURSES

View all Courses

Keep Exploring