Skip to content

Python set pop method | Example code

  • by

Use the pop() method to remove an element from a set in Python. It will remove a random item from the set and returns the removed value.

set.pop()

Python set pop element example

Simple example code pop element from the set and the set is updated (new set does not contain the removed element).

Note: If the set is empty, the TypeError exception is raised.

my_set = {'A', 'B', 'C', 'D'}

ele = my_set.pop()

print(ele)
print(my_set)

Output: Your output could be different because it returns and removes a random element.

Python set pop method

Python code to illustrate the pop() method on an empty set

empty_set = {}

ele = empty_set.pop()

print(ele)
print(empty_set)

Output: TypeError: pop expected at least 1 arguments, got 0

Do comment if you have any doubts or suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading