Python Set pop() method
Python Set pop() method
The set.pop() method in Python removes an arbitrary element (random item) from the set and returns the element removed.
Syntax
set.pop()
Parameter
NA
Return
This method returns an arbitrary (random) element from the set.
Example 1
# Python program explaining
# the set.pop() method
#initializing set1
set1 = {"mango", "banana", "apple", "tomato"}
# printing the removed value
print("Element removed from set:",value)
# printing the set after pop method
print("After the popping the value\nNew Set: ", set1)
print("\nRemoving element for the second time...")
# again removing a random item from the set
value= set1.pop()
# printing the removed value
print("Element removed from set:",value)
# printing the set after pop method
print("After the popping the value\nNew Set: ", set1)
Output
Actual Set 1: {'mango', 'banana', 'tomato', 'apple'}
Element removed from set: mango
After the popping the value
New Set: {'banana', 'tomato', 'apple'}
Removing element for the second time...
Element removed from set: banana
After the popping the value
New Set: {'tomato', 'apple'}
Example 2
# Python program explaining
# the set.pop() method
# initializing an empty set
Set = {}
print("Original Set:",Set)
# Popping the elements and printing them
# will raise an TypeError as their is 0 elements in the set
print(Set.pop())
# The New set
print("Updated set is", Set)
Output
Original Set: {}
Traceback (most recent call last):
File "main.py", line 9, in <module>
print(Set.pop())
TypeError: pop expected at least 1 arguments, got 0
