Python Set pop()
Python Set x.pop()
method removes and returns an element from the set x
.
In this tutorial, we will learn the syntax of set.pop() method and go through examples covering different scenarios for the arguments that we pass to pop() method.
Syntax
The syntax of set.pop() method is
</>
Copy
set.pop()
Examples
1. Pop an element from set
In the following program, we will take a set x
and remove an element from the set.
Python Program
</>
Copy
x = {'apple', 'banana', 'cherry'}
#remove an item
e = x.pop()
print('Item removed :', e)
print('Resulting set :', x)
#remove another item
e = x.pop()
print('\nItem removed :', e)
print('Resulting set :', x)
Program Output
Item removed : cherry
Resulting set : {'banana', 'apple'}
Item removed : banana
Resulting set : {'apple'}
2. Pop an element from empty set
In the following program, we will take an empty set x
and try to pop an item from the set.
Python Program
</>
Copy
x = set()
#remove an item
e = x.pop()
print('Item removed :', e)
print('Resulting set :', x)
Program Output
Traceback (most recent call last):
File "example.py", line 4, in <module>
e = x.pop()
KeyError: 'pop from an empty set'
set.pop() raises KeyError if the set is empty.
Conclusion
In this Python Tutorial, we learned about Python set method pop(). We have gone through the syntax of pop() method, and its usage with example programs.