在各种任务中,我们需要从一个列表中删除或提取元素。我们通常使用pop()
方法和remove()
方法来完成这个任务。在这篇文章中,我们将讨论python中pop()方法和remove()方法的主要工作区别。
pop()方法
pop()
方法是用来从一个给定的列表中提取一个元素。当在一个列表上调用时,它接受元素的index
作为可选的输入参数,并在从列表中删除元素后返回给定索引的元素,如下图所示。
myList = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", myList)
element = myList.pop(2)
print("The popped element is:", element)
print("The updated list is:", myList)
输出。
The original list is: [1, 2, 3, 4, 5, 6, 7]
The popped element is: 3
The updated list is: [1, 2, 4, 5, 6, 7]
如果我们没有提供任何索引作为输入参数,它将删除最后一个索引的元素并返回值。
myList = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", myList)
element = myList.pop()
print("The popped element is:", element)
print("The updated list is:", myList)
输出。
The original list is: [1, 2, 3, 4, 5, 6, 7]
The popped element is: 7
The updated list is: [1, 2, 3, 4, 5, 6]
remove()方法
remove()
方法也被用来从列表中删除一个元素。remove()
方法,当在一个列表上调用时,将需要被删除的元素的值作为输入参数。执行后,它从列表中删除了输入元素的第一次出现。你可以在下面的例子中观察到这一点。
myList = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", myList)
myList.remove(3)
print("The removed element is:", 3)
print("The updated list is:", myList)
输出。
The original list is: [1, 2, 3, 4, 5, 6, 7]
The removed element is: 3
The updated list is: [1, 2, 4, 5, 6, 7]
remove()
方法并不返回任何值。
Pop和Remove之间的区别
pop()
方法和remove()
方法的主要区别是:pop()
方法使用元素的索引来删除它,而remove()
方法将元素的值作为输入参数来删除该元素,正如我们在上面已经看到的。pop()
方法可以在没有输入参数的情况下使用。另一方面,如果我们使用没有输入参数的remove()
方法,程序会出现错误。pop()
方法返回被删除的元素的值。而remove()
方法则不返回任何值。- 如果我们在一个空的列表上调用
pop()
方法,它将引发一个IndexError
异常。另一方面,如果我们在一个空的列表上调用remove()
方法,它将引发ValueError
异常。
总结
在这篇文章中,我们讨论了 python 中列表的 pop() 方法和 remove() 方法的区别。