Python 列表 insert(index, element) 方法可在任意位置插入元素,理解其索引規則(特別是負索引行為)對正確操作序列至關重要。本文透過實例詳細說明正負索引插入效果與底層機制。
list.insert(index, element)
index:插入位置,新元素將佔據此索引,原有元素及之後右移element:任意 Python 物件None (原地修改)
li = ['a', 'b']
li.insert(0, 'c') # 索引 0:插入到最前面
print(li) # ['c', 'a', 'b']
li.insert(1, 'x') # 索引 1:插入到第 2 位
print(li) # ['c', 'x', 'a', 'b']
li.insert(100, 'z') # 索引超過長度:等同 append,插到最後
print(li) # ['c', 'x', 'a', 'b', 'z']
li = ['a', 'b']
li.insert(-1, 'c') # 索引 -1:倒數第 1 位「之前」插入
print(li) # ['a', 'c', 'b']
li.insert(-2, 'x') # 索引 -2:倒數第 2 位「之前」插入
print(li) # ['a', 'x', 'c', 'b']
li.insert(-100, 'y') # 負索引絕對值超過長度:等同 insert(0),插到最前
print(li) # ['y', 'a', 'x', 'c', 'b']
列表: [ 'a' , 'b' ] 索引: 0 1 負索引: -2 -1 insert(-1, 'c') → 在索引 -1 (即 'b') 之前插入 → [ 'a', 'c', 'b' ] insert(-2, 'x') → 在索引 -2 (即 'a') 之前插入 → [ 'x', 'a', 'c', 'b' ]
li = ['a', 'b']
li[1:1] = ['c'] # 等同 insert(1, 'c')
li[-1:-1] = ['x'] # 等同 insert(-1, 'x')
li[len(li):] = ['z'] # 等同 append('z')
insert(0, x) 在大列表頭部插入為 O(n),需移動所有元素collections.deque (appendleft 為 O(1))extend 後排序
# 錯誤:以為 insert(-1) 是插到最後
li = [1, 2]
li.insert(-1, 99) # 結果 [1, 99, 2] 而非 [1, 2, 99]
# 正確:插到最後用 append 或 insert(len(li), x)
li.append(99) # [1, 2, 99]
li.insert(len(li), 99) # 同理
牢記 insert(index, x) 讓 x 成為新的 index 位置元素,負索引按「倒數第 N 位之前」插入,即可避免 90% 的插入位置錯誤。