my_set={'a','b','c','d','e'}
my_set.clear()
print(my_set)
Output is here
set()
my_set={'a','b','c','d','e'}
del my_set
print(my_set)
Here we will removed the set object by using del, so the last line will generate the error ( NameError)
Use Case for clear(): The clear() method is useful when we need to empty a set while keeping the set object intact for future operations. This ensures you don't lose the reference to the set.
The clear() method removes all elements from the set but keeps the set object, whereas del deletes the set object entirely.
# Using clear()
my_set = {'apple', 'banana', 'cherry'}
my_set.clear() # Empties the set
print(my_set) # Output: set()
# Using del
my_set = {'apple', 'banana', 'cherry'}
del my_set # Deletes the set object
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.