Tutorial Study Image

Python append()

Python 中的 append() 函数用于将给定项添加到现有列表的末尾。


list.append(item) #where item can be numbers, strings, dictionaries etc
 

append() 参数

append() 函数接受一个参数。

参数 描述 必需/可选
要添加到列表末尾的项 必需

append() 返回值

此方法不返回任何值,这意味着它返回 None。实际上,此方法会更新现有列表。

Python 中 append() 方法的示例

示例 1:append() 在 Python 中如何工作?


# 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']

示例 2:如何使用 append() 将列表添加到列表中


# 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']]