pop() é uma função embutida em Python que remove e devolve o último valor da lista ou o valor do índice dado.
Sintax :
list_name.pop(index)
Parâmetro :
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.
Revoluções :
The last value or the given index value from the list
Excepção :
br>
When index is out of range, it returns IndexError
Código #1 :
div>
br>>/p>
br>>>/p>
/div>
>div>
>div>
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"
) br>>>/div>
Eliminar :
6New List after pop : 4('cat', 'bat')3New List after pop :
Código #2 :
br>>/p>
>br>>>/p>
>div>
>div>
list1 = print(list1.pop(), list1) print(list1.pop(0), list1) br>>>/div>
p> Saída :
6 1
Código #3 : IndexError
/p>
>br>>/p>
/div>
>div>>>br>
list1 = print(list1.pop(8)) Eliminar :
Traceback (most recent call last): File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in print(list1.pop(8))IndexError: pop index out of range
>br>Exemplo prático :
Uma fruta da lista contém nome_da_fruta e propriedade dizendo a sua fruta. Outra lista de consumo tem dois itens: sumo e comida. Com a ajuda de pop() e append() podemos fazer algo interessante.
>/p>
>div>
>div>
fruit =,, ] consume = possible = foritem infruit : foruse inconsume : item.append(use) possible.append(item) item.pop(-1 print(possible) br>>>/div>
p> Saída :
, , , , , ]
Etiquetas de artigos :
Etiquetas de Prática :