The python pop() method removes and returns a random element from a set. However, It will generate a keyerror exception if the value is popped from an empty set.

Python Set pop():

In order to remove a specific item from a set, we have to use the discard or remove method. Whereas if we wish to remove random elements then the pop method is suitable to perform the task.

Method signature

The signature for the pop() method is as shown below. Here, s1 refers to a set from which we will pop an element and store it in a variable v.

v=s1.pop()

Method parameters and return type

  • The pop() method doesn’t take any parameter
  • However, it returns one random element from the set.

Python Set Pop Examples:

Example 1: In this example, let us take a set s1 with a set of numbers. Thereafter, we will call a pop method that removes and returns one random element from the set.

#Initializing the Set
s1 = {99,3,14,13,34,36}
#Printing a set
print("Before pop ",s1)
# Poping random element and printing 
v=s1.pop()
print("Value poped is ",v)
#Printing a set after pop
print("After Pop ",s1)

Output

Before pop  {34, 3, 99, 36, 13, 14}
Value poped is  34
After Pop  {3, 99, 36, 13, 14}

Example 2: In this example, let us consider a set containing cities. Here, We will pop multiple elements out by making call to pop method multiple times.

#Intializing the Set
p1 = {"Delhi", "Bhopal", "Chennai", "Jodhpur"}
#Printing the Set
print ("Before pop Set is",p1)
# Using pop method and printing the value removed
print("First value popped is ",p1.pop())
print("Second value popped is ",p1.pop())
# Printing a Set 
print("Now, Set will be ",p1)

Output

Before pop Set is {'Chennai', 'Bhopal', 'Jodhpur', 'Delhi'}
First value popped is  Chennai
Second value popped is  Bhopal
Now, Set will be  {'Jodhpur', 'Delhi'}

Example 3: In this example, let us demonstrate the pop() method on a mixed set. Also, If we try to pop an element from an empty set then, it will raise a KeyError Exception. As a result of which program terminates from that point.

#Intializing the Set
c1 = {"Sam",25,88.5}
# Printing a Set
print ("Before pop ",c1)
# Using pop method and printing the value removed each time
print("First value popped is ",c1.pop())
print("Second value popped is ",c1.pop())
print("Third value popped is ",p1.pop())
print("Fourth value popped is ",p1.pop())

Output

Before pop  {88.5, 25, 'Sam'}
First value popped is  25
Second value popped is  88.5
Third value popped is  Sam
Traceback (most recent call last):
  File "main.py", line 8, in 
    print("Fourth value popped is ",c1.pop())
KeyError: 'pop from an empty set'

Conclusion

The pop() method deletes and returns a random element from a set. However, if the set is empty then it raises a KeyError Exception. Hence program terminates abnormally.

References

Happy Learning 🙂

Leave A Comment