list.pop()
Removes an item from a list by position and gives it back to you. With no argument it takes the last item.
list.pop([i])pop() takes an item out of the list and returns it, so you can use it straight away. Without an argument it removes the last item; with an index it removes the item at that position.
Together with list.append(), pop() turns a list into a stack: the last item you put in is the first one you take out, like a pile of plates. That is how undo history and back buttons usually work.
Calling pop() on an empty list, or with an index that does not exist, raises an IndexError. And pop(0) on a long list is slow, because every other item has to move one place left.
Parameters
| Parameter | What it is |
|---|---|
ioptional, default -1 | The position of the item to remove. -1 is the last item, 0 the first. Negative numbers count from the end. Give it by position, pop(0); pop(i=0) raises TypeError. |
Return value
The item that was removed.
Examples
1Take the last item
stack = ["page1", "page2", "page3"]
last = stack.pop()
print(last)
print(stack)page3 ['page1', 'page2']
2Remove by position
runners = ["Lena", "Omar", "Yuki", "Sam"]
first = runners.pop(0)
second = runners.pop(1)
print(first, second)
print(runners)Lena Yuki ['Omar', 'Sam']
After the first pop(0) the list is shorter, so index 1 now points to "Yuki", not "Omar".
3An undo history
history = []
for action in ["type A", "type B", "bold"]:
history.append(action)
print("Undo:", history.pop())
print("Undo:", history.pop())
print("Left:", history)Undo: bold Undo: type B Left: ['type A']
4Work through a to-do list until it is empty
todo = ["email", "report", "call"]
while todo:
task = todo.pop()
print("Doing", task)
print("All done:", todo)Doing call Doing report Doing email All done: []
while todo: keeps going as long as the list is not empty, so pop() is never called on an empty list.
Common mistakes
Popping from an empty list
This raises IndexError. Check that the list has items before you call pop().
items = []
if items:
print(items.pop())
else:
print("Nothing to pop")
try:
items.pop()
except IndexError:
print("IndexError: the list is empty")Nothing to pop IndexError: the list is empty
Passing a value instead of a position
pop() wants an index. To remove the item "Ben", use remove("Ben"), or pop(names.index("Ben")) if you also need it back.
names = ["Ana", "Ben", "Chloe"]
gone = names.pop(names.index("Ben"))
print(gone, names)Ben ['Ana', 'Chloe']
Questions people ask
What is the difference between pop() and remove()?
pop(i) removes by position and returns the item. list.remove() removes by value and returns None.
How do I remove the first item of a list?
items.pop(0). For a queue that you take from the front all the time, use collections.deque and popleft(), which stays fast for any length.
Does pop() work on dictionaries and sets too?
Yes, but differently: dict.pop() removes a key you name, and set.pop() removes an arbitrary element.