Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to insert an element into sorted list
In this article, we will learn how to insert an element into a sorted list while maintaining the sorted order. This is a common operation when working with ordered data structures.
Problem statement − We are given a sorted list, and we need to insert an element while preserving the sorted order.
There are two main approaches to solve this problem ?
Using Linear Search (Brute Force)
This approach searches for the correct position linearly and inserts the element ?
def insert_linear(sorted_list, element):
# Find the correct position to insert
for i in range(len(sorted_list)):
if sorted_list[i] > element:
# Insert at position i
sorted_list.insert(i, element)
return sorted_list
# If element is larger than all elements, append at end
sorted_list.append(element)
return sorted_list
# Example with numbers
numbers = [1, 3, 5, 7, 9]
new_element = 6
result = insert_linear(numbers.copy(), new_element)
print("Original list:", [1, 3, 5, 7, 9])
print("After inserting", new_element, ":", result)
Original list: [1, 3, 5, 7, 9] After inserting 6 : [1, 3, 5, 6, 7, 9]
Using the bisect Module
The bisect module provides efficient binary search functions for sorted lists ?
import bisect
def insert_bisect(sorted_list, element):
# insort automatically finds correct position and inserts
bisect.insort(sorted_list, element)
return sorted_list
# Example with numbers
numbers = [1, 3, 5, 7, 9]
new_element = 6
result = insert_bisect(numbers.copy(), new_element)
print("Original list:", [1, 3, 5, 7, 9])
print("After inserting", new_element, ":", result)
Original list: [1, 3, 5, 7, 9] After inserting 6 : [1, 3, 5, 6, 7, 9]
Example with Strings
Both methods work with strings as well ?
import bisect
# Using bisect with strings
words = ['apple', 'banana', 'orange', 'zebra']
new_word = 'mango'
# Using bisect.insort
bisect.insort(words, new_word)
print("Sorted list with 'mango':", words)
Sorted list with 'mango': ['apple', 'banana', 'mango', 'orange', 'zebra']
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Linear Search | O(n) | O(1) | Small lists |
| bisect Module | O(log n) | O(1) | Large sorted lists |
Conclusion
Use the bisect module for efficient insertion into sorted lists, especially for large datasets. The linear search approach is simpler but less efficient for large lists. Both methods maintain the sorted order of the list.
