Python List pop()函数,用于返回和删除项目教程及示例

列表是Python编程语言的重要组成部分。 pop() 函数用于列表和数组,以便从列表或数组中返回最新的项。在本教程中,我们将学习如何使用 pop() 函数从列表中删除最新的项或指定的项。

null

pop()函数语法

pop() 函数有非常简单的语法,我们不提供任何参数或单个参数。

LIST.pop(INDEX)
  • `LIST`是存储多个元素的列表、数组或类似数据类型。
  • `INDEX`是要删除的项的索引号。如果没有提供最新的项目将被退回并从列表中删除。在python中,索引号从0开始,而不是从1开始。

这个 pop() 函数将返回要弹出的项。如果提供的索引号不存在以下错误 IndexError: popo index out of range 将返回错误。

不带索引号的弹出窗口

最流行的用法是调用 pop() 没有索引号的函数。这将返回给定列表或数组的最新项。在下面的示例中,我们将运行pop()函数两次。

mylist = ['Ankara','Istanbul','Canakale','London','Munih']item = mylist.pop()print(item)# The output will be Munihprint(mylist)# The output will be ['Ankara', 'Istanbul', 'Canakale', 'London']item2 = mylist.pop()print(item)# The output will be Munihprint(mylist)# The output will be ['Ankara', 'Istanbul', 'Canakale']
Pop without and Index Number 
不带索引号的弹出窗口

当我们第一次调用pop()函数时,它返回 'Munih' 我们将返回的项设置到名为 item . 然后我们列出 mylist 在哪里 'Munih' 已删除。

相关文章: 如何在Python中对列表排序?

给定索引号的Pop

我们也可以使用 pop() 函数以返回和删除某个特定项是否为最后一项。我们将提供要返回并从给定列表中删除的索引号。在本例中,我们将返回并删除索引号为2和3的项。请记住,索引号从0开始,其中第2项是 'Canakkale' .

mylist = ['Ankara','Istanbul','Canakale','London','Munih']item = mylist.pop(2)print(item)#The output will be Canakaleprint(mylist)#The output will be ['Ankara', 'Istanbul', 'London', 'Munih']

索引号为负数的弹出窗口

pop()函数也可以用于负数。如果我们想以负数表示的相反方式返回和删除项,这将非常有用。

>>> mylist = ['Ankara','Istanbul','Canakale','London','Munih']>>> >>> item = mylist.pop(-2)>>> >>> print(item)London>>> >>> print(mylist)['Ankara', 'Istanbul', 'Canakale', 'Munih']>>> >>> >>> >>> item = mylist.pop(-3)>>> >>> print(item)Istanbul>>> >>> print(mylist)['Ankara', 'Canakale', 'Munih']>>>
Pop with Negative Index Number
索引号为负数的弹出窗口

弹出索引超出范围错误

当使用索引号和 pop() 我们可能得到的功能 Index Out Of Range Error 它只是试图获取一个不存在的索引号或项目。例如,如果我们试图从只有4个项目的列表中获取第7个项目或第6个索引号,我们将得到 Index Out Of Range Error .

mylist = ['Ankara','Istanbul','Canakale','London']item = mylist.pop(6)Traceback (most recent call last):File "", line 1, in IndexError: pop index out of rangeitem = mylist.pop(5)Traceback (most recent call last):File "", line 1, in IndexError: pop index out of rangeitem = mylist.pop(4)Traceback (most recent call last):File "", line 1, in IndexError: pop index out of range>>> item = mylist.pop(3)print(item)# The output will be London
Pop Index Out Of Range Error
弹出索引超出范围错误
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享