Python清单pop()函数返回和删除示例的示例教程

本文详细介绍了Python中列表的pop()函数,包括无索引参数的用法,弹出指定索引的元素,使用负索引以及处理索引超出范围的错误。通过实例展示了如何有效使用pop()进行列表操作。
摘要由CSDN通过智能技术生成

Lists are an important part of the Python programming language. pop() function is used with lists and arrays in order to return the latest item from the list or array. In this tutorial we will learn how to use pop() function removes the latest item or specified item from a list.

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

pop()函数语法 (pop() Function Syntax)

pop() function has very simple syntax where we provide none or single argument.

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

LIST.pop(INDEX)
  • `LIST` is the list, array or similar data type which stores multiple elements.

    LIST是存储多个元素的列表,数组或类似数据类型。
  • `INDEX` is the index number of the item we want to remove. If not provided the latest item will be returned and removed from the LIST. In python, the index numbers start from 0, not 1.

    “ INDEX”是我们要删除的商品的索引号。 如果未提供,则将返回最新项目并将其从LIST中删除。 在python中,索引号从0开始,而不是1。

The pop() function will return the item we want to pop. If an index number is provided which does not exist an error like IndexError: popo index out of range error will be returned.

pop()函数将返回我们要弹出的项目。 如果提供的索引号不存在,则会返回类似IndexError: popo index out of range的错误IndexError: popo index out of range error。

流行不带索引号 (Pop without and Index Number)

The most popular usage case is calling pop() function without index number. This will return the latest item of the given list or array. In this following example, we will run pop() function two times.

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

mylist = ['Ankara','Istanbul','Canakale','London','Munih']
item = mylist.pop()

print(item)
# The output will be Munih
print(mylist)
# The output will be ['Ankara', 'Istanbul', 'Canakale', 'London']


item2 = mylist.pop()
print(item)

# The output will be Munih
print(mylist)
# The output will be ['Ankara', 'Istanbul', 'Canakale']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值