How to Use the Python pop() Function

Python’s pop() removes an item and returns it in one step. On a list, orders.pop() takes the last item; on a dictionary, order.pop("coupon") takes the value stored under that key.

orders = ["ORD-1041", "ORD-1042", "ORD-1043"]
orders.pop()            # 'ORD-1043' (the list keeps the first two)

order = {"customer": "Emily Carter", "coupon": "FALL10"}
order.pop("coupon")     # 'FALL10' (the key is gone)

That return value is the whole point. If you don’t need the item back, del or remove() does the job too.

In this tutorial, I’ll show you how Python pop() works on lists, dictionaries, sets, deques and pandas DataFrames, using an order-fulfillment queue from a Denver warehouse.

I ran every snippet in Python 3.12.5 and pandas 3.0.6, and the screenshots are from Command Prompt.

What does pop() do in Python?

pop() is a method, not a built-in function, so you call it on an object. These types have one:

TypeSyntaxRemovesIf nothing to remove
listlst.pop([index])item at index (default: last)IndexError
dictd.pop(key[, default])the key and its valueKeyError unless you pass a default
dictd.popitem()the last inserted pairKeyError
sets.pop()an arbitrary elementKeyError
dequeq.pop() / q.popleft()right end / left endIndexError
DataFramedf.pop(column)a whole column (as a Series)KeyError

Tuples and strings are immutable, so they have no pop(). Calling it raises AttributeError: 'tuple' object has no attribute 'pop'.

If that distinction is fuzzy, read mutable vs immutable in Python.

Python list pop(): remove the last item

Here’s the warehouse queue. The newest order sits at the end, so a plain pop() takes it off:

orders = ["ORD-1041", "ORD-1042", "ORD-1043", "ORD-1044", "ORD-1045"]

latest = orders.pop()
print("Popped:", latest)
print("Left:  ", orders)

Output:

Popped: ORD-1045
Left:   ['ORD-1041', 'ORD-1042', 'ORD-1043', 'ORD-1044']
Python pop function removing the last order ID from a list, run in the terminal
pop() returned “ORD-1045”, and four orders are left in the list.

The list shrinks in place; pop() doesn’t build a new list. Popping from the end is also fast, because nothing has to shift.

For more ways to drop the tail of a list, see how to remove the last element from a list.

Pop by index: pop(0), pop(1) and negative indexes

Pass an index to remove that position. Negative numbers count from the end, just like slicing:

orders = ["ORD-1041", "ORD-1042", "ORD-1043", "ORD-1044", "ORD-1045"]

first = orders.pop(0)
second_to_last = orders.pop(-2)
middle = orders.pop(1)

print(first, second_to_last, middle)
print(orders)

Output:

ORD-1041 ORD-1044 ORD-1043
['ORD-1042', 'ORD-1045']

The first call returned “ORD-1041”, then pop(-2) took “ORD-1044” and pop(1) took “ORD-1043”. Two orders are left.

Watch the order of calls: each pop() changes the positions of everything after it. I cover index-based removal in more depth in removing a list element by index.

If you only need the oldest item off the front, removing the first element compares pop(0), slicing and del.

Use pop() to build a stack (undo history)

append() plus pop() turns a list into a last-in, first-out stack. I use it for undo features, like this invoice editor:

history = []

for edit in ["set qty=3", "apply coupon FALL10", "set shipping=2-day"]:
    history.append(edit)
    print("did: ", edit)

while history:
    print("undo:", history.pop())

Output:

did:  set qty=3
did:  apply coupon FALL10
did:  set shipping=2-day
undo: set shipping=2-day
undo: apply coupon FALL10
undo: set qty=3

The edits come back in reverse: the shipping change is undone first and the quantity change last. while history: stops on its own once the list is empty.

Depth-first search uses the same pattern; see depth-first search in Python.

Common list pop() errors

Three calls fail most often. Here’s the real message for each, plus a safe pop for empty lists:

orders = []

for call in ("orders.pop()", "['ORD-1041'].pop(5)", "['ORD-1041'].pop(index=0)"):
    try:
        eval(call)
    except (IndexError, TypeError) as err:
        print(f"{call:<26} -> {type(err).__name__}: {err}")

next_order = orders.pop() if orders else None
print("Safe pop on an empty list:", next_order)

Output:

orders.pop()               -> IndexError: pop from empty list
['ORD-1041'].pop(5)        -> IndexError: pop index out of range
['ORD-1041'].pop(index=0)  -> TypeError: list.pop() takes no keyword arguments
Safe pop on an empty list: None

An empty list gives “pop from empty list”, a bad index gives “pop index out of range”, and pop(index=0) fails because list.pop() only takes a positional argument.

orders.pop() if orders else None returns None instead of crashing. Use it when an empty queue is normal, not a bug.

The dictionary version of this error is a KeyError; fixing KeyError in Python walks through it.

Python dictionary pop(): remove a key and get its value

Same warehouse, now one order record. pop(key) removes the key and hands back its value:

order = {"order_id": "ORD-1041", "customer": "Emily Carter",
         "city": "Denver", "total": 249.99, "coupon": "FALL10"}

coupon = order.pop("coupon")
gift_note = order.pop("gift_note", "")
print("coupon:", repr(coupon), "| gift_note:", repr(gift_note))
print(order)

try:
    order.pop("coupon")
except KeyError as err:
    print("KeyError:", err)

Output:

coupon: 'FALL10' | gift_note: ''
{'order_id': 'ORD-1041', 'customer': 'Emily Carter', 'city': 'Denver', 'total': 249.99}
KeyError: 'coupon'
Python dictionary pop with a key, a default value and the KeyError for a missing key
The coupon “FALL10” came back, the missing gift_note returned the default “”, and a second pop raised KeyError.

The second argument is your safety net. order.pop("gift_note", "") returned an empty string instead of raising, so you don’t need a try block or an in check first.

More options live in removing an item from a dictionary and removing a key without an error.

Rename dictionary keys with pop()

Because pop() returns the value, one line moves it to a new key. I do this when an API sends camelCase fields and the rest of the code expects snake_case:

payload = {"orderId": "ORD-1042", "zipCode": "80202", "shipCity": "Denver"}

for old, new in [("orderId", "order_id"), ("zipCode", "zip"), ("shipCity", "city")]:
    payload[new] = payload.pop(old)

print(payload)

Output:

{'order_id': 'ORD-1042', 'zip': '80202', 'city': 'Denver'}

Each renamed key moves to the end, since dictionaries keep insertion order. That’s usually fine for JSON payloads.

dict.popitem(): remove the last inserted pair

popitem() takes no key. Since Python 3.7 it removes the most recently added pair, so it works as a stack of key-value pairs:

cart = {}
cart["SKU-100 desk lamp"] = 2
cart["SKU-205 monitor arm"] = 1
cart["SKU-310 USB-C hub"] = 3

print(cart.popitem())
print(cart.popitem())
print(cart)

Output:

('SKU-310 USB-C hub', 3)
('SKU-205 monitor arm', 1)
{'SKU-100 desk lamp': 2}

The USB-C hub came off first, then the monitor arm, leaving only the desk lamp. On an empty dictionary it raises KeyError: 'popitem(): dictionary is empty'.

Python set pop(): which element does it remove?

A set has no order, so set.pop() removes an arbitrary element. It isn’t random by design, but for strings it changes between runs because of hash randomization:

import os
import subprocess
import sys

code = 'pending = {"ORD-1041", "ORD-1042", "ORD-1043"}; print(pending.pop())'
for seed in ("1", "2", "3"):
    env = {**os.environ, "PYTHONHASHSEED": seed}
    out = subprocess.run([sys.executable, "-c", code], env=env,
                         capture_output=True, text=True).stdout.strip()
    print(f"run with PYTHONHASHSEED={seed}: popped {out}")

try:
    set().pop()
except KeyError as err:
    print("KeyError:", err)

Output:

run with PYTHONHASHSEED=1: popped ORD-1043
run with PYTHONHASHSEED=2: popped ORD-1042
run with PYTHONHASHSEED=3: popped ORD-1043
KeyError: 'pop from an empty set'
Python set pop returning a different order ID on each run with a different PYTHONHASHSEED
The same three-item set popped ORD-1043, ORD-1042, ORD-1043 across three runs, and an empty set raised KeyError.

Never use set.pop() when you need a specific item or the oldest one. Use it when any item will do, such as handing the next free job to a worker.

To remove a known value instead, see how to remove an item from a set.

pop(0) vs deque.popleft() for queues

pop(0) works, but every remaining item shifts left, so it’s O(n). collections.deque pops from either end in O(1). I timed both on 50,000 items:

from collections import deque
from timeit import timeit

N = 50_000
list_s = timeit("while q: q.pop(0)", setup=f"q = list(range({N}))", number=1)
deque_s = timeit("while q: q.popleft()",
                 setup=f"from collections import deque; q = deque(range({N}))", number=1)
print(f"list.pop(0) x {N:,}:      {list_s:.3f} s")
print(f"deque.popleft() x {N:,}: {deque_s:.3f} s")
print(f"deque is about {list_s / deque_s:.0f}x faster here")

tickets = deque(["TCK-501", "TCK-502", "TCK-503"])
print("serve first:", tickets.popleft(), "| newest:", tickets.pop(), "| left:", list(tickets))

Output:

list.pop(0) x 50,000:      3.874 s
deque.popleft() x 50,000: 0.001 s
deque is about 3237x faster here
serve first: TCK-501 | newest: TCK-503 | left: ['TCK-502']