Skip to main content

Python Set pop() Function

The Set pop() method removes random element from a Set and returns it. If the set is empty, the method raises KeyError.

warning

The set is modified in-place. No new set is returned.

note

If you want to remove a specific element, use remove() method or discard() method.

Syntax

my_set.pop()

pop() Parameters

Python Set pop() function does not take any parameters.

pop() Return Value

Python Set pop() function returns a removed item from the set.

danger

The pop() method raises a TypeError exception if the set is empty.

Examples

Example 1: Pop an Element from a Set

When you remove an item from the set using pop() method, it removes it and returns its value.

names = {'Tom', 'David', 'Anna', 'Ryan'}
element = names.pop(3)

print(element) # Output: Anna

output

Anna
note

You may get a different output every time you run this example, because pop() method returns and removes a random element.

Example 2: Pop an Element from an Empty Set

Using pop() method on an empty set raises a KeyError exception.

names = set() # create empty set
element = names.pop() # raises KeyError

output

Traceback (most recent call last):
File "main.py", line 2, in <module>
element = names.pop()
KeyError: 'pop from an empty set'