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 & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.