Python - Inserting item in sorted list maintaining order

In this article, we are going to learn how to insert an item in a sorted list while maintaining the order. Python has a built-in module called bisect that helps us insert any element in the appropriate position in the list efficiently.

Using bisect.insort()

The bisect.insort() method uses binary search to find the correct insertion point and inserts the element while maintaining the sorted order ?

# importing the module
import bisect

# initializing the list, element
numbers = [10, 23, 27, 32]
element = 25

# inserting element using bisect.insort(list, element)
bisect.insort(numbers, element)

# printing the list
print(numbers)
[10, 23, 25, 27, 32]

Multiple Insertions

You can insert multiple elements one by one, and each will be placed in the correct position ?

import bisect

numbers = [10, 20, 30, 40]
elements_to_insert = [15, 35, 5]

for element in elements_to_insert:
    bisect.insort(numbers, element)

print(numbers)
[5, 10, 15, 20, 30, 35, 40]

Manual Approach vs bisect

Here's a comparison between manual insertion and using bisect ?

import bisect
import time

# Manual approach
def manual_insert(sorted_list, element):
    for i, item in enumerate(sorted_list):
        if element < item:
            sorted_list.insert(i, element)
            return
    sorted_list.append(element)

# Test with large list
large_list1 = list(range(0, 1000, 2))  # [0, 2, 4, ..., 998]
large_list2 = large_list1.copy()

# Using bisect
start_time = time.time()
bisect.insort(large_list1, 501)
bisect_time = time.time() - start_time

# Manual approach
start_time = time.time()
manual_insert(large_list2, 501)
manual_time = time.time() - start_time

print(f"Bisect approach: {bisect_time:.6f} seconds")
print(f"Manual approach: {manual_time:.6f} seconds")
print(f"Bisect is {manual_time/bisect_time:.2f}x faster")
Bisect approach: 0.000015 seconds
Manual approach: 0.000089 seconds
Bisect is 5.93x faster

Key Points

Method Time Complexity Best For
bisect.insort() O(n) Maintaining sorted order efficiently
Manual insertion O(n) Understanding the algorithm
Insert + sort O(n log n) Multiple insertions at once

Conclusion

The bisect.insort() method efficiently maintains sorted order using binary search to find the insertion point. It's faster than manual iteration and much more efficient than inserting and re-sorting the entire list.

Updated on: 2026-03-25T12:23:21+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements