AppDividend
Latest Code Tutorials

Python Set clear() Method: Complete Guide

The clear() method removes all elements from the set.

Python Set clear()

To empty the set in Python, use the set.clear() method. The clear() method removes all elements from the set. 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.

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, and 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 have printed that set.

After that, we have 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 then use Python set remove() or Python set discard() method.

See also

Python set add()

Leave A Reply

Your email address will not be published.

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