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.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.