Python Set pop() Method

The set.pop() method removes and returns a random element from the set.

set.pop() Syntax:

set.pop()

Parameters:

No parameters.

Return type:

Returns the element that is removed from the set.

The following example demonstrates the set.pop() method.

Example: pop()
cities = {'Mumbai','Chicago','New York'}

city = cities.pop()
print('Poped element 1: ', city)
print("Updated set: ", cities)

city = cities.pop()
print('Poped element 2: ', city)
print("Updated set: ", cities)

city = cities.pop()
print('Poped element 3: ', city)
print("Updated set: ", cities)

#city = cities.pop() # throws error
Output
Poped element 1: New York
Updated set: {'Chicago', 'Mumbai'}

Poped element 2: Mumbai
Updated set: {'Chicago'}

Poped element 3: Chicago
Updated set: {}

In the above example, the 'pop()' method returns an element randomly and removes it from the set on each call. It raises TypeError when calling the pop() method on an empty set.

Example:
cities = {}
removedCity = cities.pop()
Output
Traceback (most recent call last):
    removedCity = cities.pop()
TypeError: pop expected at least 1 arguments, got 0
Want to check how much you know Python?