在这篇文章中,我们将看到如何从 清单 在python中。
使用list.pop()
我们可以用 清单 .pop() 从列表中删除第一个元素的方法。
listOfFruits = ['Orange','Apple', 'Grapes','Mango']
print("List Of Fruits are:",listOfFruits)
removedFruit = 清单 OfFruits.pop(0)
print("List Of Fruits after removing first element:",listOfFruits)
print("Removed Fruit:",removedFruit)
输出:
删除第一个元素后的水果清单:[‘Apple’, ‘Grapes’, ‘Mango’]
Removed Fruit: 橙子
如果列表为空,pop将引发索引错误。
使用del语句
我们可以使用del语句先删除
元件。
listOfFruits = ['Orange','Apple', 'Grapes','Mango']
print("List Of Fruits are:",listOfFruits)
del 清单 OfFruits[0]
print("List Of Fruits after removing first element:",listOfFruits)
输出:
删除第一个元素后的水果清单:[‘Apple’, ‘Grapes’, ‘Mango’]
如果列表为空,则在尝试访问 索引超出范围.
使用切片
We can also use slicing to remove the first 元件。 We can get a sublist
of elements except the first 元件。
listOfFruits = ['Orange','Apple', 'Grapes','Mango']
print("List Of Fruits are:",listOfFruits)
listOfFruits = 清单 OfFruits[1:]
print("List Of Fruits after removing first element:",listOfFruits)
输出:
删除第一个元素后的水果清单:[‘Apple’, ‘Grapes’, ‘Mango’]
请注意,切片操作将返回一个新列表,因此不建议使用此方法。我们显然可以将列表分配给旧列表。
使用remove()
我们也可以使用清单’s remove()
method to remove first element from the 清单 . remove method takes value as argument and removes the first occurrence of value specified.
listOfFruits = ['Orange','Apple', 'Grapes','Mango']
print("List Of Fruits are:",listOfFruits)
listOfFruits.remove(listOfFruits[0])
print("List Of Fruits after removing first element:",listOfFruits)
输出:
删除第一个元素后的水果清单:[‘Apple’, ‘Grapes’, ‘Mango’]
它抛出 索引错误 如果列表为空。
那’关于如何从python列表中删除第一个元素的所有内容