Insert Multiple Values Into a Sorted List in Python
Insert multiple values into an already-sorted list while keeping it sorted using the bisect.insort function.
Python code
14 linesimport bisect
def insert_sorted(sorted_list, values):
for value in values:
bisect.insort(sorted_list, value)
return sorted_list
if __name__ == "__main__":
original = [1, 3, 5, 7, 9]
new_values = [4, 6, 2, 8, 0]
result = insert_sorted(original, new_values)
print(f"Original: {original}")
print(f"Inserted: {new_values}")
print(f"Result: {result}")
Output
Original: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Inserted: [4, 6, 2, 8, 0]
Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
How it works
The bisect module provides insort which inserts an element into a list while maintaining sorted order. The loop calls insort for each value, and because insertion happens in place, the original list gets mutated. The function returns the same list object, so original and result refer to the same list after the function call.
Common mistakes
- Forgetting that `bisect.insort` modifies the list in place, so the original list is changed.
- Not realizing that `insort` is O(n) per insertion due to the list shifting, leading to O(n*m) overall for m insertions.
- Using the function on a list that is not already sorted, which will produce incorrect order.
Variations
- Use `bisect.insort` with a key function in Python 3.10+ for complex objects.
- For large sets of values, consider using `sort()` after extending the list with all values at once for better performance.
Real-world use cases
- Maintaining a leaderboard in a game where new scores arrive continuously and must stay sorted.
- Inserting events into a time-sorted log while preserving chronological order.
- Adding items to a sorted inventory list in an e-commerce system without re-sorting the whole list.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.