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']
Timing of list pop(0) versus deque popleft on 50,000 items in Python
On this run, list.pop(0) took 3.874 s and deque.popleft() took 0.001 s.

That’s about 3237x faster for the deque on this machine; your numbers will differ, but the gap grows with the list. For a first-in, first-out ticket queue, reach for deque.

If items need a priority instead of arrival order, use a priority queue in Python.

Why pop() inside a for loop skips items

This bug shows up in code reviews all the time. Popping from the list you’re looping over shifts the next item into the slot the loop just checked:

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

buggy = orders.copy()
for i, item in enumerate(buggy):
    if item.endswith("shipped"):
        buggy.pop(i)
print("pop inside for:", buggy)

fixed = orders.copy()
for i in range(len(fixed) - 1, -1, -1):
    if fixed[i].endswith("shipped"):
        fixed.pop(i)
print("pop backwards: ", fixed)
print("comprehension: ", [o for o in orders if not o.endswith("shipped")])

Output:

pop inside for: ['ORD-1042 shipped', 'ORD-1043 pending', 'ORD-1045 pending']
pop backwards:  ['ORD-1043 pending', 'ORD-1045 pending']
comprehension:  ['ORD-1043 pending', 'ORD-1045 pending']
Python pop inside a for loop skipping items, compared with popping backwards and a list comprehension
The buggy loop left “ORD-1042 shipped” behind; looping backwards and the comprehension both keep only the pending orders.

Looping backwards works because a pop only shifts items you’ve already checked. A list comprehension is clearer and builds a new list, which I’d pick unless you must change the list in place.

For more loop patterns, see the Python for loop guide.

pandas DataFrame.pop(): remove a column

pandas has its own pop(). It removes a column from the DataFrame and returns it as a Series:

import pandas as pd

df = pd.DataFrame({"order_id": ["ORD-1041", "ORD-1042", "ORD-1043"],
                   "city": ["Denver", "Austin", "Seattle"],
                   "total": [249.99, 89.50, 132.00],
                   "internal_note": ["VIP", "", "check address"]})

notes = df.pop("internal_note")
print(notes.tolist())
print(df)

Output:

['VIP', '', 'check address']
   order_id     city   total
0  ORD-1041   Denver  249.99
1  ORD-1042   Austin   89.50
2  ORD-1043  Seattle  132.00

The notes column came back as a list of three values, and the DataFrame kept order_id, city and total. It’s handy before exporting data you don’t want to share.

To drop columns without keeping them, use drop(); see how to delete columns in a pandas DataFrame.

Python pop vs remove vs del

All three delete from a list, but only pop() gives the item back:

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

print("pop(1)      returns", repr(orders.pop(1)), "->", orders)
print("remove(...) returns", repr(orders.remove("ORD-1042")), "->", orders)
del orders[0]
print("del [0]     returns nothing ->", orders)

Output:

pop(1)      returns 'ORD-1042' -> ['ORD-1041', 'ORD-1043', 'ORD-1042']
remove(...) returns None -> ['ORD-1041', 'ORD-1043']
del [0]     returns nothing -> ['ORD-1043']
pop()remove()del
Finds the item byindex (default last)value (first match)index or slice
Returnsthe removed itemNonenothing (it’s a statement)
Missing itemIndexErrorValueErrorIndexError
Works on dictsyes, by keynoyes, del d[key]

remove("ORD-1042") deleted only the first match and returned None. Pick pop() when you need the value, remove() when you only know the value, and del for slices.

Four more cleanup guides pair well with pop():

Frequently asked questions

What does pop() do in Python?

It removes an item from a list, dictionary, set or deque and returns it. On a list it takes the last item unless you pass an index.

What is the difference between pop() and remove() in Python?

pop() removes by index and returns the item. remove() removes the first matching value and returns None.

How do I pop from a dictionary without an error?

Pass a default: d.pop("key", None) returns None instead of raising KeyError when the key is missing.

Is pop(0) slow in Python?

On a list, yes for big lists: every remaining item shifts. Use collections.deque and popleft() for queues.

Can I use pop() on a tuple or a string?

No. Both are immutable, so they have no pop(). Convert to a list first, or slice to build a new value.

Where is list.pop() documented?

See More on Lists in the official Python tutorial.