Python set Method - clear()

The clear() method in Python is used to remove all the elements from a set. The method modifies the original set in place and does not return anything.

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

refer ‮tfigi:ot‬idea.com
set.clear()

Here, set refers to the set from which all the elements need to be removed.

Example:

# Creating a set
my_set = {1, 2, 3}

# Clearing the set
my_set.clear()

# Displaying the modified set
print(my_set)   # Output: set()

In the above example, the clear() method is used to remove all the elements from the set my_set. The original set is modified and the output shows an empty set. If the set is already empty, the clear() method has no effect. It is important to note that the clear() method modifies the original set in place, so if you want to preserve the original set, you should make a copy of it before clearing.