0
0
PythonHow-ToBeginner · 3 min read

How to Insert Into a Sorted List in Python Quickly

To insert an element into a sorted list in Python while keeping it sorted, use the bisect.insort() function. It finds the correct position and inserts the element efficiently without needing to sort the list again.
📐

Syntax

The bisect.insort(list, item) function inserts item into list at the correct position to keep it sorted.

Here:

  • list: Your sorted list.
  • item: The value you want to insert.

This function modifies the list in place.

python
import bisect

bisect.insort(sorted_list, item)
💻

Example

This example shows how to insert numbers into a sorted list using bisect.insort(). The list stays sorted after each insertion.

python
import bisect

sorted_list = [10, 20, 30, 40, 50]
print("Original list:", sorted_list)

bisect.insort(sorted_list, 35)
print("After inserting 35:", sorted_list)

bisect.insort(sorted_list, 5)
print("After inserting 5:", sorted_list)

bisect.insort(sorted_list, 60)
print("After inserting 60:", sorted_list)
Output
Original list: [10, 20, 30, 40, 50] After inserting 35: [10, 20, 30, 35, 40, 50] After inserting 5: [5, 10, 20, 30, 35, 40, 50] After inserting 60: [5, 10, 20, 30, 35, 40, 50, 60]
⚠️

Common Pitfalls

One common mistake is inserting an element using list.append() or list.insert() without keeping the list sorted. This breaks the sorted order.

Always use bisect.insort() to keep the list sorted automatically.

python
sorted_list = [10, 20, 30, 40, 50]

# Wrong way: just append - list will not stay sorted
sorted_list.append(25)
print("After append 25:", sorted_list)

# Right way: use bisect.insort
import bisect
bisect.insort(sorted_list, 25)
print("After insort 25:", sorted_list)
Output
After append 25: [10, 20, 30, 40, 50, 25] After insort 25: [10, 20, 25, 30, 40, 50, 25]
📊

Quick Reference

  • bisect.insort(list, item): Insert item into list keeping it sorted.
  • bisect.bisect(list, item): Find position to insert item but does not insert.
  • Use insort for automatic insertion.
  • Do not use append or insert alone on sorted lists.

Key Takeaways

Use bisect.insort() to insert elements into a sorted list while keeping it sorted.
bisect.insort() modifies the list in place and finds the correct position automatically.
Avoid using append() or insert() directly on sorted lists as it breaks the order.
The bisect module is efficient and designed for sorted list operations.
Remember to import bisect before using insort.