Tutorial Study Image

Python clear()

The clear()  function in python is used to delete all the elements from the set.


clear() Parameters:

clear() method doesn't take any parameters. For removing a specific element from the Set we can use remove() or discard() method.

clear() Return Value

clear() method doesn't return any value (returns None). It updates the set by making it empty.

Examples of clear() method in Python

Example 1: How to remove all elements from a set using clear()?

# set of alphabet 
alphabets = {'a', 'b', 'c','d'}
print('Alphabets (before clear):', alphabets )

# clearing alphabets 
alphabets .clear()
print('Alphabets (after clear):', alphabets )


Alphabets (before clear): {'a', 'b', 'c','d'}
Alphabets (after clear): set()

Example 2: How to clear a number set?

# Numbers set
numbers = {1, 2, 3, 4, 5}

# Set before clear()
print("Original Set is:", numbers)

# removing all the elements from the set

# Set after clear()
print("Updated Set is:", numbers)


Original Set is: {1, 2, 3, 4, 5}
Updated  Set is: set()