pop() ist eine eingebaute Funktion in Python, die den letzten Wert aus der Liste oder den angegebenen Indexwert entfernt und zurückgibt.
Syntax :
list_name.pop(index)
Parameter :
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.
Rückgaben:
The last value or the given index value from the list
Ausnahme :
When index is out of range, it returns IndexError
Code #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") Ausgabe :
6New List after pop : 4('cat', 'bat')3New List after pop :
Code #2 :
list1 =
print(list1.pop(), list1)
print(list1.pop(0), list1) Ausgabe :
6 1
Code #3 : IndexError
list1 = print(list1.pop(8)) Ausgabe :
Traceback (most recent call last): File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in print(list1.pop(8))IndexError: pop index out of range
Praxisbeispiel :
Eine Liste fruit enthält fruit_name und die Eigenschaft, die die Frucht angibt. Eine andere Liste consume hat zwei Elemente juice und eat. Mit Hilfe von pop() und append() können wir etwas Interessantes machen.
fruit =,, ] consume = possible = foritem infruit :
foruse inconsume : item.append(use)
possible.append(item) item.pop(-1) print(possible) Ausgabe :
, , , , , ]
Artikel-Tags :
Praxis-Tags :