Python - 添加列表项
添加项
要将项添加到列表末尾,请使用 append() 方法。
示例
使用 append()
方法添加一项
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
自己动手试一试 »
插入项
要在指定索引处插入列表项,请使用 insert()
方法。
insert()
方法将在指定索引处插入一个项
示例
将项插入第二个位置
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)
自己动手试一试 »