pop() jest wbudowaną funkcją w Pythonie, która usuwa i zwraca ostatnią wartość z listy lub podaną wartość indeksu.
Syntaktyka :
list_name.pop(index)
Parametr :
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.
Zwraca :
The last value or the given index value from the list
Wyjątek :
When index is out of range, it returns IndexError
Kod #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") Wyjście :
6New List after pop : 4('cat', 'bat')3New List after pop :
Kod #2 :
list1 =
print(list1.pop(), list1)
print(list1.pop(0), list1) Wyjście :
6 1
Kod #3 : IndexError
list1 = iv
print(list1.pop(8)) Wyjście :
Traceback (most recent call last): File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in print(list1.pop(8))IndexError: pop index out of range
Praktyczny przykład :
Lista fruit zawiera fruit_name i właściwość mówiącą o jej owocu. Inna lista consume ma dwa elementy juice i eat. Za pomocą funkcji pop() i append() możemy zrobić coś ciekawego.
fruit =,, ]
consume = possible =
for
foritem infruit :
foruse inconsume :
item.append(use)
possible.append(item)
item.pop(-1)
print(possible) Wyniki :
, , , , , ]
Tagi artykułów :
Tagi dotyczące praktyki :