set.pop() Pop arbitrary element
Last updated: 2026-09-22
set.pop() Pop arbitrary element
set.pop() removes and returns an arbitrary element; raises KeyError if empty.
| Category | Set Methods |
|---|---|
| Kind | Built-in Type Method |
| Python Version | all |
📝 Syntax
set.pop()
Returns:An arbitrary popped element; raises KeyError if the set is empty.
Mutates the original:Yes (in place)
💥 Raises
KeyError— Raised when the set is empty.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
1
{2, 3}
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhich element does pop() pop?
AAn arbitrary one. Sets are unordered, so you cannot predict which element is popped - this is the biggest difference from list.pop(), which always pops the last.
QWhat happens when called on an empty set?
AA KeyError: 'pop from an empty set' is raised.
QHow do I empty a set one element at a time?
AUse the while s: item = s.pop() loop pattern, but the final pop raises a KeyError, so guard with if s: or catch the exception first.