To clear all of the data from the set data structure, use the python set clear method. All of the elements from the set will be cleared. We’ll be leaving with an empty set.
To see a clear technique in action, follow the steps below.
- Create a new set.
- Clear the set with the clear method.
- When you print the set, you’ll notice that one of the boxes is blank.
Syntax:
set.clear()
Set clear() Parameters
The clear() method has no parameters.
Return value from Set clear()
This method has no return value; it simply removes all of the elements from the set.
Example 1: Remove all elements from a Python set using clear()
# set of vowels
vowels = {'a', 'e', 'i', 'o', 'u'}
print('Vowels (before clear):', vowels)
# clearing vowels
vowels.clear()
print('Vowels (after clear):', vowels)
Output
Vowels (before clear): {'e', 'a', 'o', 'u', 'i'}
Vowels (after clear): set()
Questions
How do I remove a set in Python?
There are 2 methods to remove a set in Python: discard() method and remove() method.
Leave a Reply