Reference Materials
Created with over a decade of experience.
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python Set Methods
- Python Set remove()
- Python Set add()
- Python Set copy()
- Python Set clear()
- Python Set difference()
- Python Set difference_update()
- Python Set discard()
- Python Set intersection()
- Python Set intersection_update()
- Python Set isdisjoint()
- Python Set issubset()
- Python Set pop()
- Python Set symmetric_difference()
- Python Set symmetric_difference_update()
- Python Set union()
- Python Set update()
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.
Also Read:
Did you find this article helpful?
