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.
Syntax
set.pop()
Examples
# Remove random item from a set
S = {'red', 'green', 'blue'}
S.pop()
print(S)
# Prints {'green', 'red'}
When you remove an item from the set using pop()
, it removes it and returns its value.
S = {'red', 'green', 'blue'}
x = S.pop()
print(x)
# Prints blue
pop()
method raises KeyError on empty set.
S = set()
S.pop()
# Triggers KeyError: 'pop from an empty set'