Python Set pop()

Python Set pop() method

Python set pop() method removes a random item from the set and returns the removed item.

In this tutorial, you will learn the syntax and usage of Set pop() method, with examples.

Syntax of Set pop()

The syntax to call pop() method is

set.pop()

Parameters

Set pop() method takes no parameters.

Return value

The Set pop() method returns the removed item.

Please note that the pop() method modifies the original set.

Usage

The following statement shows how to remove an item from a set set_1 and store the removed item in a variable.

removed_item = set_1.pop()

Examples

1. Popping an element from Set in Python

In this example, we shall take a set of strings in set_1 and remove a random item from the set. We shall store the removed item in a variable, and then print it to output.

Python Program

# Take a set
set_1 = {'apple', 'banana', 'cherry'}

# Pop an item
removed_item = set_1.pop()

print(f"Removed item : {removed_item}")
print(f"Updated set  : {set_1}")
Run Code Copy

Output

Removed item : cherry
Updated set  : {'apple', 'banana'}

If you run the program in your system, or rerun the program, you may get different output at different runs. This is because, an item from the set is removed randomly.

2. Removing items iteratively from a set, until empty, in Python

In this example, we shall remove the items iteratively in a Python while else loop, until the set is empty.

Python Program

# Take a set
set_1 = {'apple', 'banana', 'cherry'}

# Pop an item
while set_1:
    removed_item = set_1.pop()
    print(removed_item)
else:
    print('Set is empty.')
Run Code Copy

Output

apple
cherry
banana
Set is empty.

When all the items in the set are removed, the while loop breaks.

Summary

In this Python Set Tutorial, we learned how to use pop() method to remove item(s) from a set in Python, with the help of well detailed examples programs.

Related Tutorials

Code copied to clipboard successfully 👍