Python set Method - pop()

https‮/:‬/www.theitroad.com

The pop() method in Python sets is used to remove and return an arbitrary element from the set. The pop() method raises a KeyError exception if the set is empty.

The syntax for the pop() method is as follows:

set_name.pop()

Here, set_name is the name of the set from which we want to remove and return an arbitrary element.

Example:

# Creating a set
fruits = {"apple", "banana", "cherry"}

# Removing an arbitrary element using pop()
removed_fruit = fruits.pop()

print("Removed fruit:", removed_fruit)   # Output: Removed fruit: banana
print("Remaining fruits:", fruits)        # Output: Remaining fruits: {'cherry', 'apple'}

In the above example, the pop() method is used to remove and return an arbitrary element from the set fruits. The removed element is assigned to the variable removed_fruit. The output shows that the element banana is removed from the set, and the remaining elements are apple and cherry.