Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.pop() method

Reference for Python set.pop(): remove and return an arbitrary element, the KeyError on an empty set, why the order is not guaranteed and safe patterns.

The pop() method removes one element from a set and returns it. Sets have no order, so you cannot choose which element comes out: Python picks one for you.

Calling pop() on an empty set raises KeyError. Because the choice is arbitrary, use pop() when you only need "any one item", for example when draining a work list, and not when you need a particular one.

Python
tags = {"a", "b", "c"}
item = tags.pop()   # one of "a", "b", "c"

Try it

Python Draining a set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Empty sets and alternatives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
set.pop()

The method takes no arguments (unlike list.pop(), which accepts an index).

Return value: the removed element.

Raises: KeyError if the set is empty. The error message is 'pop from an empty set'.

Usage notes

  • Arbitrary, not random. The element depends on the internal hash table, so it can change between runs and between Python versions. For strings, hashing differs from run to run unless PYTHONHASHSEED is fixed. Do not rely on any order.
  • Mutates the set and returns the element, so there is no way to pop without removing.
  • Check before popping. Use if values: or catch KeyError. There is no default argument.
  • Small integers often come out in order in CPython, but this is an implementation detail and not a promise.
  • Need a specific element? Use remove() (raises KeyError if missing) or discard() (silent).
  • Need to take the smallest or largest? Use min() or max(), or keep a heap, because sets do not keep ordering.
  • Frozensets cannot pop, because they are immutable.