Efficiently Inserting Elements into a Sorted List with bisect
Owner: SnippetBot
Created: 2026-09-29 00:00:32
Size: 1.45 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import bisect
# An already sorted list
my_sorted_list = [10, 20, 30, 40, 50]
print(f"Original list: {my_sorted_list}")
# bisect_left returns an insertion point which comes before (to the left of) any existing entries of x in a.
insert_pos_left = bisect.bisect_left(my_sorted_list, 30)
print(f"Insertion point for 30 (left): {insert_pos_left}") # index of the existing 30
# bisect_right (or just bisect) returns an insertion point which comes after (to the right of) any existing entries of x in a.
insert_pos_right = bisect.bisect_right(my_sorted_list, 30)
print(f"Insertion point for 30 (right): {insert_pos_right}") # index after the existing 30
# Inserting a new value while maintaining sort order
# bisect.insort_left inserts before any existing entries of x
bisect.insort_left(my_sorted_list, 25)
print(f"List after insort_left(25): {my_sorted_list}")
bisect.insort_right(my_sorted_list, 30) # inserts after the existing 30
print(f"List after insort_right(30): {my_sorted_list}")
# More insertions
bisect.insort(my_sorted_list, 5) # defaults to insort_right
print(f"List after insort(5): {my_sorted_list}")
bisect.insort(my_sorted_list, 55)
print(f"List after insort(55): {my_sorted_list}")
# Using bisect_left/bisect_right to find a range
# Find all numbers between 20 and 40 (exclusive of 40)
start_index = bisect.bisect_left(my_sorted_list, 20)
end_index = bisect.bisect_left(my_sorted_list, 40)
print(f"Numbers between 20 and 40: {my_sorted_list[start_index:end_index]}")