Skip to content
Related Articles

Related Articles

Improve Article

Python Set | pop()

  • Last Updated : 08 Aug, 2021

This in-built function of Python helps to pop out elements from a set just like the principle used in the concept while implementing Stack. This method removes a top element from the set but not the random element and returns the removed element. 

We can verify this by printing the set before using the pop() method.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Syntax: 



# Pops a First 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'}

 

Python3




# Python code to illustrate pop() method
 
S = {"ram", "rahim", "ajay", "rishav", "aakash"}
 
# Print the set before using pop() method
# First element after printing the set will be popped out
print(S)
 
# Popping three elements and printing them
print(S.pop())
print(S.pop())
print(S.pop())
 
# The updated set
print("Updated set is", S)

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. 
 

Python3




# 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)

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
Recommended Articles
Page :