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 次浏览

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.