當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python list pop()用法及代碼示例


pop()是Python中的內置函數,可從列表或給定的索引值中刪除並返回最後一個值。

用法:

list_name.pop(index)

參數:


index (optional) - The value at index is 
popped out and removed.

If the index is not given, then the last
element is popped out and removed.

返回值:

The last value or the given index value from the list

異常:

When index is out of range, it returns IndexError


代碼1:

# Python3 program for pop() method 
  
list1 = [ 1, 2, 3, 4, 5, 6 ] 
  
# Pops and removes the last element from the list 
print(list1.pop()) 
  
# Print list after removing last element 
print("New List after pop:", list1, "\n") 
  
list2 = [1, 2, 3, ('cat', 'bat'), 4] 
  
# Pop last three element 
print(list2.pop()) 
print(list2.pop()) 
print(list2.pop()) 
  
# Print list 
print("New List after pop:", list2, "\n")

輸出:

6
New List after pop: [1, 2, 3, 4, 5] 

4
('cat', 'bat')
3
New List after pop: [1, 2] 


代碼2:

# Python3 program showing pop() method 
# and remaining list after each pop 
  
list1 = [ 1, 2, 3, 4, 5, 6 ] 
  
# Pops and removes the last  
# element from the list 
print(list1.pop(), list1) 
  
# Pops and removes the 0th index 
# element from the list 
print(list1.pop(0), list1)

輸出:

6 [1, 2, 3, 4, 5]
1 [2, 3, 4, 5]


代碼3: IndexError

# Python3 program for error in pop() method 
  
list1 = [ 1, 2, 3, 4, 5, 6 ] 
print(list1.pop(8))

輸出:

Traceback (most recent call last):
  File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in 
    print(list1.pop(8))
IndexError:pop index out of range


實際示例:
列表中的水果包含fruit_name和表示其水果的屬性。另一個清單上的消費有兩項果汁和食物。借助pop()和append(),我們可以做一些有趣的事情。

# Python3 program demonstrating 
# practical use of list pop() 
  
fruit = [['Orange','Fruit'],['Banana','Fruit'], ['Mango', 'Fruit']] 
consume = ['Juice', 'Eat'] 
possible = [] 
  
# Iterating item in list fruit 
for item in fruit:
      
    # Inerating use in list consume 
    for use in consume:
          
        item.append(use) 
        result.append(item[:]) 
        item.pop(-1) 
print(result)

輸出:

[['Orange', 'Fruit', 'Juice'], ['Orange', 'Fruit', 'Eat'],
 ['Banana', 'Fruit', 'Juice'], ['Banana', 'Fruit', 'Eat'],
 ['Mango', 'Fruit', 'Juice'], ['Mango', 'Fruit', 'Eat']]



注:本文由純淨天空篩選整理自Striver大神的英文原創作品 Python list | pop()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。