set.pop()
set.pop() any · Updated March 15, 2026 · Set Methods The .pop() method removes and returns an arbitrary element from a set. Since sets are unordered collections, which element gets removed is not guaranteed — it appears random, though in Python 3.7+ it’s actually the oldest element based on insertion order. This method is useful when you need to process and remove elements one at a time without regard to their specific values.
Syntax
set.pop()
Parameters
The .pop() method takes no parameters.
Return Value
Returns the removed element, which can be of any hashable type.
Raises
KeyError— if the set is empty
Examples
Basic usage
Remove and retrieve an arbitrary element:
fruits = {"apple", "banana", "cherry"}
item = fruits.pop()
print(f"Removed: {item}")
print(f"Remaining: {fruits}")
# Removed: banana (or apple, or cherry)
# Remaining: {'apple', 'cherry'}
The exact element removed varies, but the operation succeeds and returns whatever was removed.
Empty set raises KeyError
Attempting to pop from an empty set raises an error:
empty = set()
try:
empty.pop()
except KeyError:
print("Cannot pop from empty set")
# Cannot pop from empty set
This is different from list .pop(), which returns None when the list is empty.
Checking before popping
Always check if the set is empty before popping:
def safe_pop(s):
if s:
return s.pop()
return None
numbers = {1, 2, 3}
print(safe_pop(numbers)) # 2 (or 1, or 3)
print(safe_pop(set())) # None
Processing all elements
Use .pop() in a loop to process every element:
queue = {"task1", "task2", "task3"}
completed = []
while queue:
task = queue.pop()
print(f"Processing: {task}")
completed.append(task)
print(f"All done: {completed}")
# Processing: task2 (or any order)
# Processing: task1
# Processing: task3
# All done: ['task2', 'task1', 'task3']
Draining a set completely
Remove all elements efficiently:
items = {"a", "b", "c", "d"}
collected = []
while items:
collected.append(items.pop())
print(collected)
# ['a', 'b', 'c', 'd'] # in some order
This is equivalent to converting to a list but lets you process each element as you go.
Random selection alternative
If you need a specific random element, use the random module:
import random
colors = {"red", "green", "blue"}
selected = random.choice(list(colors))
print(f"Randomly selected: {selected}")
# Randomly selected: green
Set to list conversion
Convert a set to a list (different from pop, doesn’t modify original):
my_set = {10, 20, 30}
as_list = list(my_set)
print(as_list)
# [10, 20, 30] # order not guaranteed
Common Patterns
Implementing a simple queue
Use a set as an unordered queue:
class SetQueue:
def __init__(self):
self._data = set()
def add(self, item):
self._data.add(item)
def pop_next(self):
if not self._data:
return None
return self._data.pop()
def __len__(self):
return len(self._data)
queue = SetQueue()
queue.add("first")
queue.add("second")
queue.add("third")
while len(queue) > 0:
print(queue.pop_next())
Removing until a condition is met
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
# Remove even numbers one by one
while numbers:
num = numbers.pop()
if num % 2 == 0:
print(f"Removed even: {num}")
else:
# Put odd numbers back (they don't fit our goal)
numbers.add(num)
break # or use a different approach
print(f"Remaining: {numbers}")
Getting a representative sample
def get_sample(population, size):
sample = set()
for _ in range(min(size, len(population))):
if population:
sample.add(population.pop())
return sample
items = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print(get_sample(items, 3))
# {1, 2, 3} # or any 3 elements
Performance
The .pop() method has:
- Average case: O(1) time complexity
- Worst case: O(n) when hash collisions occur
The removal itself is constant time, but the apparent randomness comes from how Python’s hash implementation orders elements internally.
See Also
- set::set.add() — adds an element to a set
- set::set.discard() — removes an element without error if not found
- set::set.clear() — removes all elements from the set