Python Set pop() Method

Removes and returns a random item from the set

Usage

The pop() method removes random item from a set and returns it.

If the set is empty, the method raises KeyError.

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

Syntax

set.pop()

Examples

Example: Remove random item from a set

S = {'red', 'green', 'blue'}
S.pop()
print(S)    # {'green', 'red'}

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

Example:

S = {'red', 'green', 'blue'}
x = S.pop()
print(x)    # blue

pop() method raises KeyError on empty set.

Example:

# KeyError: 'pop from an empty set'
S = set()
S.pop()