在本教程中,我们将学习列表的最常用方法,即append()和extend()。让我们一一看。
附加()
append()方法用于在list的末尾插入元素。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()方法的时间复杂度为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']
结论
希望您喜欢本教程。