clear() method for set

clear() takes no argument.

Returns : No return value.
my_set={'a','b','c','d','e'}
my_set.clear()
print(my_set)
Output is here
set()

del and clear() difference

We can use keyword del to remove any object. Once it is removed then further use of it raise NameError.
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)

Understanding set.clear() in Python

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.

Comparison with del:

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

All set methods Questions with solutions on set discard()
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate 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.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer