默认情况下,Python List pop() 方法会删除并返回列表中的最后一个对象。但是,该方法还接受可选的 index 参数,并且 index 处的元素将从列表中删除。
此方法与 remove() 方法的区别在于,pop() 方法在索引技术的帮助下删除对象,而 remove() 方法遍历列表以查找对象的第一个匹配项。
语法
以下是 Python List pop() 方法的语法 -
参数
- obj − 这是一个可选参数,要从列表中删除的对象的索引。
返回值
此方法从列表中返回已删除的对象。
例以下示例显示了 Python List pop() 方法的用法。在这里,我们没有向方法传递任何参数。
当我们运行上述程序时,它会产生以下结果——
Popped Element : abc
Updated List:
[123, 'xyz', 'zara']
Updated List:
[123, 'xyz', 'zara']
例
但是,如果我们向方法传递一个 index 参数,则返回值将是在给定索引处删除的对象。
如果我们编译并运行上面的程序,输出显示如下 -
Popped Element : ghi
Updated List:
['abc', 'def', 'jkl']
Updated List:
['abc', 'def', 'jkl']
例
众所周知,Python 中允许负索引,并且是从右到左完成的。因此,当我们将负索引作为参数传递给方法时,索引中存在的元素将被删除。
执行上述程序时,输出如下 -
Popped Element : 876
Updated List:
[123, 456, 789]
Updated List:
[123, 456, 789]
例
但是,如果传递给该方法的索引大于 List 的长度,则会引发 IndexError。
让我们编译并运行给定的程序,以产生以下结果 -
Traceback (most recent call last):
File "main.py", line 2, in
print("Popped Element : ", aList.pop(5))
IndexError: pop index out of range
File "main.py", line 2, in
print("Popped Element : ", aList.pop(5))
IndexError: pop index out of range