pop() es una función incorporada en Python que elimina y devuelve el último valor de la lista o el valor del índice dado.
Sintaxis :
list_name.pop(index)
Parámetros :
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.
Devuelve :
The last value or the given index value from the list
Excepción :
When index is out of range, it returns IndexError
Código #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") Salida :
6New List after pop : 4('cat', 'bat')3New List after pop :
Código #2 :
list1 =
print(list1.pop(), list1)
print(list1.pop(0), list1) Salida :
6 1
Código #3 : IndexError
list1 =
print(list1.pop(8)) Salida :
Traceback (most recent call last): File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in print(list1.pop(8))IndexError: pop index out of range
Ejemplo práctico :
Una lista fruit contiene fruit_name y la propiedad que dice su fruta. Otra lista consume tiene dos ítems juice y eat. Con la ayuda de pop() y append() podemos hacer algo interesante.
fruit =,, ]
consume =
possible =
foritem infruit :
foruse inconsume :
item.append(use) possible.append(item) item.pop(-1)
print(possible) Salida :
, , , , , ]
Etiquetas del artículo :
Etiquetas de práctica :