« All set methods
pop() takes no argument .
Returns : removed item.
my_set={'a','b','c','d','e'}
x=my_set.pop()
print('Removed item : ', x)
print(my_set)
Output is here
Removed item : d
{'b', 'e', 'a', 'c'}
Removing all the items
We can remove all items by using while loop and each time we can display the removed item.
( This should not be used as a replacement of clear() method which removes all the items at one go ). len() function is used to get the length or number of elements present inside the set.
my_set={'a','b','c','d','e'}
while(len(my_set)):
x=my_set.pop()
print('Removed item : ', x)
print(my_set)
Output is here
Removed item : d
{'b', 'e', 'a', 'c'}
Removed item : b
{'e', 'a', 'c'}
Removed item : e
{'a', 'c'}
Removed item : a
{'c'}
Removed item : c
set()
« All set methods « Questions with solutions on set pop()
← Subscribe to our YouTube Channel here