add-remove

set.pop

Removes and returns an arbitrary element from the set. Raises KeyError if the set is empty.

s.pop()

Parameters

Parameter Purpose
(no args) pop() takes no arguments — the element chosen is implementation-defined
returns The removed element

Examples

>>> s = {10, 20, 30}
>>> x = s.pop()
>>> x in {10, 20, 30}
True

Returns some element; which one is not guaranteed.

>>> s = {'only'}
>>> s.pop()
'only'
>>> s
set()

On a one-element set the result is deterministic.

>>> s = set()
>>> s.pop()
KeyError: 'pop from an empty set'

Empty set raises KeyError.

>>> s = {1, 2, 3}
>>> while s: s.pop()
>>> s
set()

Common pattern to drain a set.

Gotcha

pop returns an ARBITRARY element — NOT the last inserted or smallest. Do not rely on which element you get; iteration order in CPython is not part of the language spec.

Related methods

← All Python set methods · List methods · list vs tuple vs set