Python - 添加列表项
追加项目
要将项目添加到列表末尾,请使用 append() 方法:
实例
使用 append() 方法添加项目:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
亲自试一试 »
插入列表项
要在指定索引处插入列表项,请使用 insert() 方法。
insert() 方法会在指定索引处插入一个列表项:
实例
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
亲自试一试 »
注意:根据以上示例,列表现在将包含 4 个项目。
扩展列表
要将另一个列表中的元素添加到当前列表,请使用extend()方法。
实例
将 tropical 的元素添加到 thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
亲自试一试 »
这些元素将被添加到列表的末尾。
添加任何可迭代对象
`extend() 方法不一定只能追加列表,您可以添加任何可迭代对象(元组、集合、字典等)。
实例
将元组的元素添加到列表中:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
亲自试一试 »

