Kodeclik Blog
Python Set pop()
Recall that a set is defined using curly braces in Python and that it doesn’t allow any duplicates. For instance, if we define a set like this and aim to print it:
mytoys = {'Bus','Car','Bus','Train'}
print(mytoys)
We will get:
{'Bus', 'Car', 'Train'}
Note that there is only one instance of “Bus” (as it should be).
The pop() method does not take any arguments and when applied on a set removes a random element from the set.
Here is a modification to the earlier program:
mytoys = {'Bus','Car','Bus','Train'}
print(mytoys)
mytoys.pop()
print(mytoys)
This will output:
{'Bus', 'Car', 'Train'}
{'Car', 'Train'}
Note that the “Bus” element has been popped from this set of toys.
If we aim to do:
mytoys = {'Bus','Car','Bus','Train'}
print(mytoys)
mytoys.pop()
mytoys.pop()
mytoys.pop()
print(mytoys)
we will get:
{'Bus', 'Car', 'Train'}
set()
Note that after three pops on a three-element set, we will obtain an empty set, or the null set denoted by set().
What does pop() return?
We mentioned that pop returns a random element but in addition the method returns the element removed. Here’s how you can use it:
mytoys = {'Bus','Car','Bus','Train'}
print(mytoys)
for x in range(3):
toy = mytoys.pop()
print(toy, " has been removed")
print(mytoys)
This program will print:
{'Bus', 'Car', 'Train'}
Bus has been removed
Car has been removed
Train has been removed
set()
Note that your output could be different because the order of elements being popped is non-deterministic. At each step we are printing the element being popped and again at the end of the iteration we are left with an empty set.
Doing pop() on an empty set
What happens if you aim to do pop() on an empty set? Here is the same program as above with an additional pop():
mytoys = {'Bus','Car','Bus','Train'}
print(mytoys)
for x in range(3):
toy = mytoys.pop()
print(toy, " has been removed")
print(mytoys)
mytoys.pop()
The output is:
{'Bus', 'Car', 'Train'}
Bus has been removed
Car has been removed
Train has been removed
set()
Traceback (most recent call last):
File "main.py", line 7, in <module>
mytoys.pop()
KeyError: 'pop from an empty set'
Note that the last pop() does not succeed because we are aiming to pop from an empty set.
If you liked this blogpost, checkout our post on more general Python set operations.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.