Python Set pop() Method

Python Set pop() method is used to remove a random element from the Set and returns the removed element.

Syntax

set.pop()

Parameters

The set is the set’s name, and this method does not take any argument as a parameter.

Return Value

It returns the removed item.  If the set is empty, it returns a TypeError exception.

Example 1: How to Use Set pop() MethodVisual Representation of How to Use Python Set pop() Method

# Declaring set
roll = {7, 9, 10, 11, 18}

# Now we will pop value from set
print("Roll which is popped: ", roll.pop())

# Printing the updated sets
print("Updated roll set is: ", roll)

Output

Roll which is popped: 18

Updated roll set is: {7, 9, 10, 11}

Example 2: Empty Set

# empty set
data ={}

# throws an error
print(data.pop())

Output

TypeError: pop expected at least 1 argument, got 0

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.