Python Set | pop()

This in-built function of Python helps to pop out elements from a set just like the principal used in the concept while implementing Stack. This method removes a random element from the set and returns the removed element. Unlike, a stack a random element is popped off the set.

Syntax:

# Pops a random element from S
# and returns it.
S.pop()

This is one of the basic functions of the set and accepts no arguments. The return value is the popped element from the set. Once the element is popped out of the set, the set loses the element and it is updated to a set without the element.

Examples:

Input : 
sets = {1, 2, 3, 4, 5}
Output : 
1
Updated set is {2, 3, 4, 5}

Input : 
sets = {"ram", "rahim", "ajay", "rishav", "aakash"}
Output :
rahim
Updated set is {'ram', 'rishav', 'ajay', 'aakash'}
filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to illustrate pop() method
  
S = {"ram", "rahim", "ajay", "rishav", "aakash"}
  
# Popping three elements and printing them
print(S.pop())
print(S.pop())
print(S.pop())
  
# The updated set
print("Updated set is", S)

chevron_right


Output:



rishav
ram
rahim
Updated set is {'aakash', 'ajay'}

On the other hand, if the set is empty, then a TypeError is returned as shown by the following program.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to illustrate pop() method
# on an empty set
S = {}
  
# Popping three elements and printing them
print(S.pop())
  
# The updated set
print("Updated set is", S)

chevron_right


Output:

No Output

Error:

Traceback (most recent call last):
  File "/home/7c5b1d5728eb9aa0e63b1d70ee5c410e.py", line 6, in 
    print(S.pop())
TypeError: pop expected at least 1 arguments, got 0


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.