Python 删除列表项

删除列表项

有几种方法可以从列表中删除项目:

例子 1

remove() 方法删除指定的项目:

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

亲自试一试

例子 2

pop() 方法删除指定的索引(如果未指定索引,则删除最后一个项目):

thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

亲自试一试

例子 3

del 关键字删除指定的索引:

thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

亲自试一试

例子 4

del 关键字也可以完全删除列表:

thislist = ["apple", "banana", "cherry"]
del thislist

亲自试一试

例子 5

clear() 方法清空列表:

thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

亲自试一试