Python Set clear()

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

Example

# set of prime numbers
primeNumbers = {2, 3, 5, 7}

# clear all elements primeNumbers.clear()
print(primeNumbers) # set()

clear() Syntax

The syntax of the clear() method is:

 
set.clear()

Here, set.clear() clears the set by removing all the elements of the set.


clear() Parameters

The clear() method doesn't take any parameters.


clear() Return Value

The clear() method doesn't return any value.


Example 1: Python Set clear()

# set of vowels
vowels = {'a', 'e', 'i', 'o', 'u'}
print('Vowels (before clear):', vowels)

# clear vowels vowels.clear()
print('Vowels (after clear):', vowels)

Output

Vowels (before clear): {'e', 'a', 'o', 'u', 'i'}
Vowels (after clear): set()

In the above example, we have used the clear() method to remove all the elements of the set vowels.

Here, once clearing the element, we get set() as output, which represents the empty set.


Example 2: clear() Method with a String Set

# set of strings
names = {'John', 'Mary', 'Charlie'}
print('Strings (before clear):', names)

# clear strings
names.clear()
print('Strings (after clear):', names)

Output

Strings (before clear): {'Charlie', 'Mary', 'John'}
Strings (after clear): set()

In the above example, we have used the clear() method to remove all the elements of the set names.

Did you find this article helpful?