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
set.remove
Removes the specified element from the set. Raises KeyError if the element is not present.
set.discard
Removes an element from the set if it is present, and does nothing otherwise. Unlike remove(), never raises an error.
set.clear
Removes all elements from the set, leaving it empty. Mutates the set in place; other references to the same set see it emptied.
set.add
Adds a single hashable element to the set in place. If the element is already present, the set is unchanged (no error).
set.update
Adds every element from each iterable argument to s in place. Equivalent to a union but mutates s instead of returning a new set.
← All Python set methods · List methods · list vs tuple vs set