7. Python pop()

发布时间:2023-12-08

Python pop()

更新:2022-07-24 13:02 Python 中的pop()函数有助于从列表的给定索引中移除元素。它还返回被移除的元素作为输出。如果未指定索引,则移除最后一个元素并返回。

list.pop(index) # where index must be a integer number

pop()参数:

pop()函数接受一个参数。如果没有传递索引参数,它将默认索引作为-1。这意味着最后一个元素的索引。

参数 描述 必需/可选
指数 要从列表中移除的对象的索引 可选择的

pop()返回值

如果传递的索引不在范围内,它将引发索引错误:弹出索引超出范围异常。为了返回第三个元素,我们需要传递 2 作为索引,因为索引从零开始。

投入 返回值
中频索引 从索引中返回元素
没有索引 返回最后一个元素

Python 中pop()方法的示例

示例 1:如何从列表中弹出给定索引处的项目?

# alphabets list
alphabets = ['a', 'b', 'c', 'd', 'e', 'f']
# remove and return the 5th item
return_value = alphabets.pop(4)
print('Return element:', return_value)
# Updated List
print('Updated List:', alphabets) 

输出:

Return element: e
Updated List:  ['a', 'b', 'c', 'd', 'f']

pop()在没有索引的情况下,对于负索引是如何工作的?

# alphabets list
alphabets = ['a', 'b', 'c', 'd', 'e', 'f']
# remove and return the last item
print('When index is not passed:') 
print('Return element:', alphabets.pop())
print('Updated List:', alphabets)
# remove and return the last item
print('\nWhen -1 is passed:') 
print('Return element:', alphabets.pop(-1))
print('Updated List:', alphabets)
# remove and return the fourth last item
print('\nWhen -4 is passed:') 
print('Return element:', alphabets.pop(-4))
print('Updated List:', alphabets) 

输出:

When index is not passed:
Return element: f
Updated List: ['a', 'b', 'c', 'd', 'e']
When -1 is passed:
Return element: e
Updated List: ['a', 'b', 'c', 'd']
When -4 is passed:
Return element: a
Updated List: ['b', 'c', 'd']