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:
We will get:
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:
This will output:
Note that the “Bus” element has been popped from this set of toys.
If we aim to do:
we will get:
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:
This program will print:
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():
The output is:
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.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.