Python 中的 pop() 函数有助于从列表的给定索引中移除元素。它还会将该被移除的元素作为其输出返回。如果未指定索引,则移除并返回最后一个元素。
list.pop(index) #where index must be a integer number
pop() 函数接受一个参数。如果未传递 index 参数,则默认为索引 -1。这意味着最后一个元素的索引。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 索引 | 要从列表中移除的对象的索引。 | 可选 |
如果传递的 index 不在范围内,它会抛出 IndexError: pop index out of range 异常。要返回第 3 个元素,我们需要传递 2 作为索引,因为索引从零开始。
| 输入 | 返回值 |
|---|---|
| 如果指定索引 | 返回指定索引处的元素 |
| 未指定索引 | 返回最后一个元素 |
# 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']
# 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']