萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 列表插入元素完整指南:insert() 方法參數詳解與負索引行為

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% 的插入位置錯誤。

copyright © 萬盛學電腦網 all rights reserved