Python 中的 append() 函数用于将给定项添加到现有列表的末尾。
list.append(item) #where item can be numbers, strings, dictionaries etc
append() 函数接受一个参数。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 项 | 要添加到列表末尾的项 | 必需 |
此方法不返回任何值,这意味着它返回 None。实际上,此方法会更新现有列表。
# flowers list
flowers = ['Rose', 'Lotus', 'Jasmine']
# 'Sunflower' is appended to the flowers list
flowers.append('Sunflower')
# Updated flowers list
print('Updated flowers list: ', flowers )
输出
Updated flowers list: ['Rose', 'Lotus', 'Jasmine', 'Sunflower']
# flowers list
flowers = ['Rose', 'Lotus', 'Jasmine']
# flowers list
flowers = ['Rose', 'Lotus', 'Jasmine']
# list of vegetables
vegetables = ['Tomato', 'Potato']
# appending vegetables list to the flowers list
flowers.append(vegetables)
print('Updated list: ', flowers)
输出
Updated list: ['Rose', 'Lotus', 'Jasmine', ['Tomato', 'Potato']]