set.pop() removes and returns an arbitrary element from a non-empty set. Because a set is unordered, your code must not depend on which element is selected.
If the set is empty, pop() raises KeyError. Use clear() when the goal is simply to remove every element without processing them one by one.
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'}
my_set={'a','b','c','d','e'}
while 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()
my_set = set()
try:
my_set.pop()
except KeyError as e:
print(f"Error: {e}") # Output: 'pop from an empty set'
my_set = {1, 2, 3, 4}
while my_set:
print(my_set.pop()) # Pops elements until the set is empty
my_set = {10, 20, 30, 40}
while my_set:
print(f"Removed: {my_set.pop()}")
print("Set is now empty.")
Output:
Removed: 40
Removed: 10
Removed: 20
Removed: 30
Set is now empty.
my_set = {1, 2}
my_set.add(3)
print(my_set.pop()) # Arbitrarily pops an element after adding 3
The set.pop() method in Python removes and returns an arbitrary element from the set because sets are unordered collections. This means pop() does not remove a first or last element. Treat the returned element as arbitrary and do not build program logic around a particular removal order.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.