Set clear() Method in Python

Python Set clear() Method

The clear() method is used to remove all elements from a set, making it an empty set. This method does not take any parameters and modifies the set in place.

Syntax of the clear() method:

your_set.clear()

Parameters:

  • your_set: This is the set from which you want to remove all elements.

Example:

# Creating a set with some elements
numbers = {1, 2, 3, 4, 5}

# Using the clear() method to remove all elements from the set
numbers.clear()

print(numbers)  # Output: set()

As you can see in the example, after calling the clear() method on the numbers set, all the elements are removed, and the set becomes empty.

Keep in mind that the clear() method modifies the set in place and does not return a new set. It directly updates the set on which it is called.