Bài toán: cho danh sách đã sắp xếp, chèn phần tử mới mà không làm mất thứ tự.
Cách 1: Brute-force
def insert(list_, n):
for i in range(len(list_)):
if list_[i] > n:
index = i
break
list_ = list_[:i] + [n] + list_[i:]
return list_
list_ = ['t','u','t','o','r']
n = 'e'
print(insert(list_, n))
['e', 't', 'u', 't', 'o', 'r']
Cách 2: Dùng module bisect
import bisect
def insert(list_, n):
bisect.insort(list_, n)
return list_
list_ = ['t','u','t','o','r']
n = 'e'
print(insert(list_, n))
['e', 't', 'u', 't', 'o', 'r']

Các biến cục bộ và tham chiếu như hình.
Kết luận
Đã học chèn phần tử vào danh sách đã sắp xếp.