pop() è una funzione integrata in Python che rimuove e restituisce l’ultimo valore dalla lista o il valore dell’indice dato.
Sintassi :
list_name.pop(index)
Parametro :
index (optional) - The value at index is popped out and removed.If the index is not given, then the lastelement is popped out and removed.
Returns :
The last value or the given index value from the list
Exception :
When index is out of range, it returns IndexError
Codice #1 :
list1 =
print(list1.pop())
print("New List after pop : ", list1, "\n") list2 = print(list2.pop())
print(list2.pop()) print(list2.pop())
print("New List after pop : ", list2, "\n") Output :
6New List after pop : 4('cat', 'bat')3New List after pop :
Codice #2 :
list1 =
print(list1.pop(), list1)
print(list1.pop(0), list1) Output :
6 1
Codice #3 : IndexError
list1 = print(list1.pop(8)) Output :
Traceback (most recent call last): File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in print(list1.pop(8))IndexError: pop index out of range
Esempio pratico :
Una lista fruit contiene fruit_name e la proprietà che dice il suo frutto. Un’altra lista consumare ha due elementi succo e mangiare. Con l’aiuto di pop() e append() possiamo fare qualcosa di interessante.
fruit =,, ] consume = possible =
foritem infruit :
foruse inconsume : item.append(use)
possible.append(item)
item.pop(-1) print(possible) Output :
, , , , , ]
Tag articolo :
Practice Tags :