AppDividend
Latest Code Tutorials

Python Set clear() Method Example Tutorial

0

Python Set clear() is an inbuilt method that is used to clear/remove all elements from the given set. After clearing everything, only the empty set present. The clear() method removes all elements from the set.

Python Set clear()

If you want to empty the set then Python set.clear() method is your solution. 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 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 using 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.