pop() method of set

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()
my_set = set()
try:
    my_set.pop()
except KeyError as e:
    print(f"Error: {e}")  # Output: 'pop from an empty set'

Example 1: Handling Empty Sets

my_set = set()
try:
    my_set.pop()
except KeyError as e:
    print(f"Error: {e}")  # Output: 'pop from an empty set'

Example 2: Using pop() in a Loop

my_set = {1, 2, 3, 4}
while my_set:
    print(my_set.pop())  # Pops elements until the set is empty

Example 3: Removing All Elements Randomly

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.

Example 4: Using pop() After Adding New Elements

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.
All set methods Questions with solutions on set pop()
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate 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.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer