Python append() - List 新增元素
append() 方法用來在 list 的末尾新增一個元素。
基本用法
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'orange']
語法
list.append(element)
element:要新增的元素- 回傳:None(直接修改原 list)
修改原 list
append() 會直接修改原 list,不會回傳新的 list:
numbers = [1, 2, 3]
result = numbers.append(4)
print(numbers) # [1, 2, 3, 4]
print(result) # None
新增不同類型的元素
my_list = []
my_list.append(1) # 數字
my_list.append("hello") # 字串
my_list.append(True) # 布林
my_list.append([1, 2, 3]) # list
my_list.append({"a": 1}) # dict
print(my_list) # [1, 'hello', True, [1, 2, 3], {'a': 1}]
append() vs extend()
append() 會將整個物件作為單一元素新增,extend() 會將可迭代物件的每個元素分別新增:
# append() - 新增為單一元素
list1 = [1, 2, 3]
list1.append([4, 5])
print(list1) # [1, 2, 3, [4, 5]]
# extend() - 展開後新增
list2 = [1, 2, 3]
list2.extend([4, 5])
print(list2) # [1, 2, 3, 4, 5]
append() vs + 運算子
# append() - 修改原 list
list1 = [1, 2, 3]
list1.append(4)
print(list1) # [1, 2, 3, 4]
# + 運算子 - 建立新 list
list2 = [1, 2, 3]
list2 = list2 + [4]
print(list2) # [1, 2, 3, 4]
append() 效率較高,因為不需要建立新的 list。
實際範例
收集資料
numbers = []
for i in range(1, 6):
numbers.append(i * 2)
print(numbers) # [2, 4, 6, 8, 10]
過濾資料
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n)
print(evens) # [2, 4, 6, 8, 10]
上面的過濾範例可以用 list comprehension 更簡潔地寫成
evens = [n for n in numbers if n % 2 == 0]讀取多行輸入
lines = []
# 模擬讀取輸入
inputs = ["Line 1", "Line 2", "Line 3"]
for line in inputs:
lines.append(line.strip())
print(lines) # ['Line 1', 'Line 2', 'Line 3']
建立堆疊(Stack)
stack = []
# Push
stack.append("first")
stack.append("second")
stack.append("third")
print(stack) # ['first', 'second', 'third']
# Pop
item = stack.pop()
print(item) # third
print(stack) # ['first', 'second']
紀錄歷史
history = []
def save_state(data):
history.append(data.copy()) # 使用 copy() 避免參照問題
current = {"x": 0, "y": 0}
save_state(current)
current["x"] = 10
save_state(current)
current["y"] = 20
save_state(current)
print(history)
# [{'x': 0, 'y': 0}, {'x': 10, 'y': 0}, {'x': 10, 'y': 20}]
常見錯誤
誤用回傳值
# 錯誤:append() 回傳 None
numbers = [1, 2, 3].append(4)
print(numbers) # None
# 正確
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # [1, 2, 3, 4]
和 extend 混淆
# 如果想要合併兩個 list
list1 = [1, 2, 3]
list2 = [4, 5]
# 錯誤:會變成巢狀 list
list1.append(list2)
print(list1) # [1, 2, 3, [4, 5]]
# 正確:使用 extend
list1 = [1, 2, 3]
list1.extend(list2)
print(list1) # [1, 2, 3, 4, 5]
時間複雜度
append() 的平均時間複雜度是 O(1),非常高效。