Python foundations

Python list.pop(): Remove and Return an Item

Use list.pop() to take the last item or pass an index to take another. See what happens on an empty list and when to use remove or del.

In Python, list.pop() removes and returns the last item. Pass a zero-based index to take a different item, or a negative index to count back from the end. The call changes the original list. An empty list or invalid index raises IndexError.

drafts = ["intro", "outline", "appendix"]
removed = drafts.pop()
assert removed == "appendix"
assert drafts == ["intro", "outline"]

first = drafts.pop(0)
assert first == "intro"
assert drafts == ["outline"]

The variable removed is now a reference to the same object that occupied the final position. The list lost a slot, but the object can still be used through that variable.

How pop handles indexes

An index selects a position. items.pop(2) takes the third item, even if the number 2 never appears in the list. Negative indexes count from the end. items.pop(-1) and items.pop() take the same item. items.pop(-2) takes the second-to-last item when the list has at least two entries.

Each removal shifts later entries left. If you remove index 1, the entry that was at index 3 moves to index 2. To remove several entries by their original positions, validate the indexes, convert any negative ones to positions in the original list, and remove the highest position first. If you want to keep entries that match a rule, a filtered list avoids having to track shifting indexes.

Handle an empty stack deliberately

There is no built-in default argument to pop() for the empty case. If an empty list means there is simply no work waiting, check it first in an ordinary single-threaded program.

pending = ["preview"]
while pending:
    job = pending.pop()
    print(f"Working on {job}")

assert pending == []

This loop has a clear end: each successful iteration takes one item and adds none. If emptiness indicates a broken program invariant, let the error explain the broken assumption or raise a clearer one at the boundary. Catching every IndexError around a long block can hide errors from an unrelated indexing operation. For a task queue shared across threads, use an appropriate queue abstraction instead of coordinating separate emptiness checks and removals yourself.

Choose between pop, remove, and del

Use pop(index) when the position and the removed value both matter. remove(value) removes the first equal entry and returns None. It raises ValueError when no entry matches. del items[index] removes by position without returning the removed value. A slice such as del items[1:3] deletes a range in place.

Those distinctions matter when equal values mean several occurrences. In a playlist with two entries named “Opening,” remove("Opening") acts on the first matching name. To take the last playlist entry, use pop(). To discard only the third slot, use del playlist[2]. The method should describe why that entry is being removed.

Pick the collection according to the removal pattern

For undo history, append followed by pop() supports the usual rule: undo the most recent action first. A list is a good fit for that stack. To handle items in arrival order, frequent pop(0) repeatedly shifts the remaining items. A deque with append and popleft gives that queue efficient operations at opposite ends. Keep a normal list when you also frequently use arbitrary positions and removals are rare.

A useful test includes the value taken out and the list left behind. A function can return the right item but leave an unexpected collection behind if it removes from an alias or uses the wrong position. Test both so the calling code's next operation gets the state it expects.

For earlier decisions about indexing, mutability, and the collection itself, see how Python lists work.

Sources and further reading

Related reading

Browse Python foundations · Explore project tutorials

Search PythonProjects.org