# Python Array Bisection Algorithm

PythonProgrammingServer Side Programming

The bisect algorithm is used to find the position in the list, where the data can be inserted to keep the list sorted. Python has a module called bisect. Using this module, we can use bisect algorithms.

To use this module, we should import it using −

import bisect


There are some bisect related operations. These are −

## Method bisect.bisect(list, element, begin, end)

This method is used to find a position in the sorted list, where the number can be placed and the list remains sorted. If the element is already present, it will return the right most position, where the number can be inserted.

## Method bisect.bisect_left(list, element, begin, end)

This method is same as the bisect() method. The only difference is, if the item is already present, this method will return the left most location to insert the data.

## Method bisect.bisect_right(list, element, begin, end)

This method is completely same as the bisect() method.

## Method bisect.insort(list, element, begin, end)

This method is used to get a sorted list after inserting the element in correct position. If element is already present, it will insert at the right most position to keep the list sorted.

## Method bisect.insort_left(list, element, begin, end)

This method is same as insort() method. The only difference is, if element is already present, it will insert at the left most position to keep the list sorted.

## Method bisect.insort_right(list, element, begin, end)

This method is completely same as insort() method.

## Example Code

Live Demo

import bisect
my_list = [11, 25, 36, 47, 56, 69, 69, 69, 78, 78, 91, 102, 120]
print('Correct Location to insert 53 is: ' + str(bisect.bisect(my_list, 53, 0, len(my_list))))
print('Correct right Location to insert 69 is: ' + str(bisect.bisect_right(my_list, 69, 0, len(my_list))))
print('Correct left Location to insert 69 is: ' + str(bisect.bisect_left(my_list, 69, 0, len(my_list))))
bisect.insort(my_list, 59, 0, len(my_list))
print(my_list)
bisect.insort_left(my_list, 78, 0, len(my_list))
print(my_list)


## Output

Correct Location to insert 53 is: 4
Correct right Location to insert 69 is: 8
Correct left Location to insert 69 is: 5
[11, 25, 36, 47, 56, 59, 69, 69, 69, 78, 78, 91, 102, 120]
[11, 25, 36, 47, 56, 59, 69, 69, 69, 78, 78, 78, 91, 102, 120]

Updated on 30-Jul-2019 22:30:23