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']