Insert an item into sorted list in Python Insert an item into sorted list in Python python python

Insert an item into sorted list in Python


Use the insort function of the bisect module:

import bisect a = [1, 2, 4, 5] bisect.insort(a, 3) print(a)

Output

[1, 2, 3, 4, 5] 


Hint 1: You might want to study the Python code in the bisect module.

Hint 2: Slicing can be used for list insertion:

>>> s = ['a', 'b', 'd', 'e']>>> s[2:2] = ['c']>>> s['a', 'b', 'c', 'd', 'e']


You should use the bisect module. Also, the list needs to be sorted before using bisect.insort_left

It's a pretty big difference.

>>> l = [0, 2, 4, 5, 9]>>> bisect.insort_left(l,8)>>> l[0, 2, 4, 5, 8, 9]timeit.timeit("l.append(8); l = sorted(l)",setup="l = [4,2,0,9,5]; import bisect; l = sorted(l)",number=10000)    1.2235019207000732timeit.timeit("bisect.insort_left(l,8)",setup="l = [4,2,0,9,5]; import bisect; l=sorted(l)",number=10000)    0.041441917419433594