Python Set pop() method explanation with example

Introduction :

Python set pop method is used to remove an element from a set and returns it. It removes a random element. For example :

set = {1,2,3,4,5}

If we use pop method, it will remove any random element from this set. The new set will not contain this element after pop is called.

Syntax of python set pop() :

The syntax of the pop method is as below :


As you can see, this method doesn’t take any parameter. It will return one random element from the set. This element is also removed from the set. So, the new set will not contain the returned element.

setA = {1, 2, 3, 4, 5, 6, 7, 8, 9}

print("setA : {}".format(setA))
print("The popped item is : {}".format(setA.pop()))
print("setA : {}".format(setA))

Sample Output :

setA : {1, 2, 3, 4, 5, 6, 7, 8, 9}
The popped item is : 1
setA : {2, 3, 4, 5, 6, 7, 8, 9}

If the set is empty, it will throw one TypeError.

setA = set()

print("The popped item is : {}".format(setA.pop()))

It will throw one TypeError.

TypeError: pop expected at least 1 arguments, got 0

Similar tutorials :

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊