Python程式中的append()和extend()


在本教程中,我們將學習**列表**最常用的方法,即**append()**和**extend()**。讓我們逐一瞭解它們。

append()

**append()**方法用於在**列表**的末尾插入元素。**append()**方法的時間複雜度為**O(1)**。

語法

list.append(element) -> element can be any data type from the list of data types.

讓我們看一些例子。

示例

# initializing a list
nums = [1, 2, 3, 4]
# displaying the list
print('----------------Before Appending-------------------')
print(nums)
print()
# appending an element to the nums
# 5 will be added at the end of the nums
nums.append(5)
# displaying the list
print('----------------After Appending-------------------')
print(nums)

輸出

如果您執行上述程式,您將獲得以下結果。

----------------Before Appending-------------------
[1, 2, 3, 4]
----------------After Appending-------------------
[1, 2, 3, 4, 5]

追加列表。

示例

# initializing a list
nums = [1, 2, 3, 4]
# displaying the list
print('----------------Before Appending-------------------')
print(nums)
print()
# appending an element to the nums
# 5 will be added at the end of the nums
nums.append([1, 2, 3, 4])
# displaying the list
print('----------------After Appending-------------------')
print(nums)

輸出

如果您執行上述程式,您將獲得以下結果。

----------------Before Appending-------------------
[1, 2, 3, 4]
----------------After Appending-------------------
[1, 2, 3, 4, [1, 2, 3, 4]]

extend()

**extend()**方法用於使用可迭代物件延長列表。**extend()**方法的時間複雜度為**O(n)**,其中n是可迭代物件的長度。

語法

list.extend(iterable) -> extend method iterates over the iterable and appends all the elements to the list.

讓我們看一些例子。

示例

# initializing a list
nums = [1, 2, 3, 4]
# displaying the list
print('----------------Before Appending-------------------')
print(nums)
print()
# extending the list nums
# 5, 6, 7 will be added at the end of the nums
nums.extend([5, 6, 7])
# displaying the list
print('----------------After Appending-------------------')
print(nums)

輸出

如果您執行上述程式,您將獲得以下結果。

----------------Before Appending-------------------
[1, 2, 3, 4]
----------------After Appending-------------------
[1, 2, 3, 4, 5, 6, 7]

如果將字串傳遞給**extend()**方法會發生什麼?讓我們看看。

示例

# initializing a list
nums = ['h', 'i']
# displaying the list
print('----------------Before Appending-------------------')
print(nums)
print()
# extending the list nums
# 5, 6, 7 will be added at the end of the nums
nums.extend('hello')
# displaying the list
print('----------------After Appending-------------------')
print(nums)

輸出

如果您執行上述程式,您將獲得以下結果。

----------------Before Appending-------------------
['h', 'i']
----------------After Appending-------------------
['h', 'i', 'h', 'e', 'l', 'l', 'o']

結論

希望您喜歡本教程。如果您對本教程有任何疑問,請在評論區提出。

更新於:2019年11月1日

436 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告