set.pop()
Removes one element from a set and returns it. You cannot choose which: sets have no order, so treat it as arbitrary.
set.pop()pop() takes an element out of a set and gives it to you. Because a set has no first or last element, Python picks whichever is handiest. It is not random in a useful sense, and it is not "the smallest" either; do not rely on which one you get.
That makes it right for one situation: you want to process every element once and do not care about the order, such as working through a pool of tasks until it is empty.
For sets of strings the element you get can even change from one run of the program to the next. That is why the examples below print the size or the sorted remainder, never the popped element itself. On an empty set, pop() raises KeyError.
Return value
The element that was removed.
Examples
1The set gets smaller by one
colors = {"red", "green", "blue"}
taken = colors.pop()
print(len(colors))
print(taken in colors)2 False
Which color was taken is not fixed, so the example only shows that one is gone.
2Process a pool of tasks until it is empty
tasks = {"wash", "cook", "shop", "iron"}
done = []
while tasks:
done.append(tasks.pop())
print(len(done), "tasks done")
print(sorted(done))
print(tasks)4 tasks done ['cook', 'iron', 'shop', 'wash'] set()
An empty set prints as set(), because {} would be an empty dictionary.
3Need a predictable element? Choose it yourself
scores = {42, 17, 88}
lowest = min(scores)
scores.remove(lowest)
print(lowest)
print(sorted(scores))17 [42, 88]
Common mistakes
Expecting pop() to return a particular element
It is not the first one you added, nor the smallest. If you need a specific one, use min(), max() or sorted() and then set.remove(). If you need order, use a list.
Popping from an empty set
This raises KeyError. Loop with while s: or check if s: first.
pool = set()
try:
pool.pop()
except KeyError:
print("KeyError: the set is empty")KeyError: the set is empty
Questions people ask
Is set.pop() random in Python?
Not truly random, but not predictable either. Treat the element as arbitrary. For a random choice use random.choice(list(s)).
Does set.pop() take an index or a value?
No arguments at all. Use set.remove() or set.discard() to remove a specific value.
How is it different from list.pop()?
list.pop() removes by position, the last item by default. Sets have no positions.