Python set pop method | Example code

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 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 and suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

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