Python Set clear: How to Clear Set

To empty the set in Python, use the set.clear() method. The clear() method removes all elements from the set.  

Python Set clear

The Set clear() is a built-in Python method that is used to clear/remove all elements from the given set. After clearing everything, only the empty set is there. Therefore, the clear() method removes all elements from the set.

Syntax

set.clear()

The clear() function does not have any parameters. But set_name is the name of your set.

Return Value

The method does not return any value, it just returns None.

See the following code example.

# app.py

# Declaring an empty set
vowels = set()
# Taking input from users
print("Enter all five vowels")
for i in range(5):
    s = input()
    vowels.add(s)

print("The set is: ", vowels)
# Clearing the set
vowels.clear()

print("After clearing the set is: ", vowels)

Output

Enter all five vowels
a
e
i
o
u
The set is:  {'e', 'a', 'u', 'o', 'i'}
After clearing the set is:  set()

Here, in this example, we have taken the input of 5 vowels from the user in the set named vowels. Then we printed that set.

After that, we used a clear() method to remove all elements from the set, and finally, we can see that the set is empty.

If you want to remove a specific element from the Set, use the Python set remove() or the set discard() method.

Leave a Comment

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