How to Clear a Set in Python?

Estimated read time 1 min read

In Python, you can clear all elements in a set by using the clear() method. The clear() method removes all the elements from a set, leaving it empty.

Here’s an example of how to use the clear() method to clear all elements in a set:

my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: set()

In this example, the clear() method is called on the my_set object, which removes all the elements from the set, leaving it empty.

Note that the clear() method modifies the original set in place and does not return a new set. If you want to create a new set with the same name as the original set, you can simply assign an empty set to it like this:

my_set = {1, 2, 3, 4, 5}
my_set = set()
print(my_set) # Output: set()

This creates a new empty set and assigns it to the my_set variable, effectively clearing all elements from the original set.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply