首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python List.insert() 方法完整教學:指定位置插入元素的核心操作

     編輯:更多程式設計知識

insert() 是 Python 列表用於在指定索引位置之前插入單一元素的方法。不同於 append()(尾端)與 extend()(批次尾端),insert() 提供精確的位置控制,是實作佇列、優先序列、有序維護等演算法的基礎工具。

語法與參數

list.insert(index, obj)
  • index:插入位置索引(0 為最前端,負數從後往前計算)
  • obj:要插入的單一物件(任意型別)

回傳值

回傳 None,原地修改列表(in-place)。

索引規則詳解

基本範例

#!/usr/bin/python
aList = [123, 'xyz', 'zara', 'abc']
aList.insert(3, 2009)
print("Final List :", aList)
# 輸出:Final List : [123, 'xyz', 'zara', 2009, 'abc']

核心範例與索引行為演示


lst = ['a', 'b', 'c']

# 索引 0:最前端
lst.insert(0, 'first')
print(lst)  # ['first', 'a', 'b', 'c']

# 索引 len:末尾(等同 append)
lst.insert(len(lst), 'last')
print(lst)  # ['first', 'a', 'b', 'c', 'last']

# 索引超出長度:自動調整為末尾
lst.insert(100, 'overflow')
print(lst)  # ['first', 'a', 'b', 'c', 'last', 'overflow']

# 負索引:從後往前
lst = ['a', 'b', 'c']
lst.insert(-1, 'before_last')  # 在 'c' 之前
print(lst)  # ['a', 'b', 'before_last', 'c']

lst.insert(-3, 'pos_neg3')     # 索引 -3 相當於 len-3 = 0
print(lst)  # ['pos_neg3', 'a', 'b', 'before_last', 'c']

insert() vs append() vs extend() 比較

索引值插入位置說明
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)批次尾端新增、列表合併

進階應用場景

1. 維護有序列表插入(二分搜尋優化)


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)  # 最大值,直接加尾端

2. 實作雙端佇列


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. 插入分隔符/標記


# 每 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, '|']

4. 切片指派替代多次 insert(批次插入更高效)


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]

效能分析

  • 時間複雜度:O(n),需將索引 i 之後的所有元素向後搬移
  • 空間複雜度:O(1) 額外空間
  • 頭端插入(index=0)最慢,尾端插入(index=len)最快(等同 append)
  • 大量隨機位置插入建議改用 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 差異、切片指派批次插入優化、迴圈插入索引偏移陷阱,能正確高效地應用於有序維護、佇列實作、資料插入等場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved