python列表pop()
时间:2020-02-23 14:42:55 来源:igfitidea点击:
在本教程中,我们将看到关于Python列表的POP方法。
python列表pop方法用于删除并返回指定索引处的元素。
Python列表pop语法
list1.pop(index) or list1.pop()
这里list1是列表的对象。
Python列表POP示例
我们可以简单地使用POP方法在给定索引处删除和返回元素。
如果我们未通过任何Parameter,则将删除并返回列表中的最后一个元素。
让我们在简单的例子的帮助下了解这一点。
listOfVehicles=['Car','Bike','Cycle','Truck'] #Let's remove bike from above list vehicleRemoved=listOfVehicles.pop(1) print("listOfVehicles:",listOfVehicles) print("Removed vehicle:",vehicleRemoved) #Let's use pop method without any argument, it will delete last element by default vehicleRemoved=listOfVehicles.pop() print("listOfVehicles:",listOfVehicles) print("Removed vehicle:",vehicleRemoved)
输出:
listOfVehicles: ['Car', 'Cycle', 'Truck'] Removed vehicle: Bike listOfVehicles: ['Car', 'Cycle'] Removed vehicle: Truck
如我们所见,如果我们不通过任何参数,则POP方法将从列表中删除最后一个元素。