insert() 是 Python 列表用於在指定索引位置之前插入單一元素的方法。不同於 append()(尾端)與 extend()(批次尾端),insert() 提供精確的位置控制,是實作佇列、優先序列、有序維護等演算法的基礎工具。
list.insert(index, obj)
回傳 None,原地修改列表(in-place)。
| 索引值 | 插入位置 | 說明 | ||
|---|---|---|---|---|
| 0 | 最前端 | 成為新的第一個元素 | ||
| len(list) | 末尾 | 等同 append() | ||
| > len(list) | 末尾 | 自動調整為末尾,不報錯 | ||
| -1 | 倒數第一個元素之前 | 即倒數第二個位置 | ||
| -len(list)-1 | 最前端 | 等同 index=0 | ||
| < -len(list)-1 | 最前端 | 自動調整為 0 |
| 方法 | 位置 | 參數 | 時間複雜度 | 適用場景 |
|---|---|---|---|---|
| insert(i, x) | 索引 i 前 | 單一物件 | O(n) | 指定位置插入、維護有序列表 |
| append(x) | 末尾 | 單一物件 | O(1) 平均 | 尾端新增、堆疊 push |
| extend(iter) | 末尾 | 可迭代物件 | O(k) | 批次尾端新增、列表合併 |
import bisect
# bisect.insort 內部使用二分搜尋找位置 + insert 插入
sorted_lst = [1, 3, 5, 7]
bisect.insort(sorted_lst, 4)
print(sorted_lst) # [1, 3, 4, 5, 7]
# 手動實作(教學用)
def insert_sorted(lst, value):
"""插入並保持升序"""
for i, x in enumerate(lst):
if value <= x:
lst.insert(i, value)
return
lst.append(value) # 最大值,直接加尾端
class Deque:
def __init__(self):
self._data = []
def push_front(self, x):
self._data.insert(0, x) # O(n)
def push_back(self, x):
self._data.append(x) # O(1)
def pop_front(self):
return self._data.pop(0) # O(n)
def pop_back(self):
return self._data.pop() # O(1)
# 注意:頻繁頭端操作建議用 collections.deque(O(1))
from collections import deque
dq = deque()
dq.appendleft(1) # O(1)
dq.append(2) # O(1)
# 每 3 個元素插入一個分隔符
data = list(range(1, 10)) # [1..9]
sep = '|'
i = 3
while i < len(data):
data.insert(i, sep)
i += 4 # 跳過剛插入的分隔符 + 原本的 3 個
print(data)
# [1, 2, 3, '|', 4, 5, 6, '|', 7, 8, 9, '|']
lst = [1, 2, 3, 4, 5]
# 想在索引 2 處插入 [10, 20, 30]
# 方法一:多次 insert(O(n²) 總時間)
for i, x in enumerate([10, 20, 30]):
lst.insert(2 + i, x)
# 方法二:切片指派(O(n) 一次搬移)
lst = [1, 2, 3, 4, 5]
lst[2:2] = [10, 20, 30]
print(lst) # [1, 2, 10, 20, 30, 3, 4, 5]
collections.deque 或 linked list 結構
# 陷阱 1:insert 回傳 None,不可鏈式呼叫
lst = [1, 2]
result = lst.insert(0, 0).append(3) # AttributeError: 'NoneType' has no attribute 'append'
# 陷阱 2:迴圈中插入導致索引偏移
lst = [1, 2, 3, 4, 5]
# 想在所有偶數前插入 0
for i, x in enumerate(lst):
if x % 2 == 0:
lst.insert(i, 0) # 錯誤!插入後後續元素索引+1,會漏檢或重複檢查
# 正確:從後往前遍歷,或建立新列表
lst = [1, 2, 3, 4, 5]
new_lst = []
for x in lst:
if x % 2 == 0:
new_lst.append(0)
new_lst.append(x)
print(new_lst) # [1, 0, 2, 3, 0, 4, 5]
insert(index, obj) 是列表指定位置插入單一元素的標準方法,原地修改、回傳 None、索引支援負數與超出範圍自動調整。核心特性為 O(n) 時間複雜度(需搬移後續元素),頭端插入最慢。掌握索引規則、與 append/extend 差異、切片指派批次插入優化、迴圈插入索引偏移陷阱,能正確高效地應用於有序維護、佇列實作、資料插入等場景。