List Methods
pop()
Remove and return the item at the specified index.
list.pop(index=-1)
list.pop() removes the item at index and returns it.
If no index is specified, it removes and returns the last item in the list (index=-1), making it ideal for stack (LIFO) operations.
Parameters
| Name | Description |
|---|---|
| index | Optional index of the item to remove. Defaults to -1 (the last item). |
Returns
The removed element.
Try it
Run it and change it
queue = ["task1", "task2", "task3"]
last_task = queue.pop()
first_task = queue.pop(0)
print("Popped last:", last_task)
print("Popped first:", first_task)
print("Remaining:", queue)Worth knowing
- IndexError: Raises
IndexErrorif the list is empty or the index is out of range. - Fastest removal: Popping from the end (
pop()) isO(1)constant time.