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(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()
my_set = set()
try:
my_set.pop()
except KeyError as e:
print(f"Error: {e}") # Output: 'pop from an empty 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()) # Randomly 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 the last element or follow any specific order when removing elements. The removal happens randomly, and the element returned could be any element from the set.
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.