Python set pop() Method

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.

Set order: sets are unordered. Whenever an example prints a set, the displayed element order can differ between runs or Python environments.
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 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()

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 with pop()

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())  # 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.
All Set Methods Questions with solutions on set pop()


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-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer