Contents
Python Set clear() method
Python Set clear() method clears all the elements in the set.
In this tutorial, you will learn how to use Python Set clear() method, with syntax and different usage scenarios, with example programs.
Syntax of Set clear()
The syntax to call clear() method on a set is
set.clear()
Parameters
Set clear() method takes no parameters.
Return value
clear() method returns None.
Please note that the clear() method modifies the original set, and contents would be lost.
Examples
1. Removing all the elements from Set in Python
In this example, we shall take a Python set with some initial elements in it. Then, we use clear method on this set, and observe the resulting set.
Python Program
# Initialize set
set_1 = {'a', 'b', 'c'}
# Clear elements of set
set_1.clear()
print(set_1)
Run Code CopyOutput
set()
The resulting set is empty. clear() modifies the original set.
2. Clearing an empty Set
If you apply clear() method on an empty set, the empty set should be unchanged.
Python Program
# Initialize set
set_1 = {}
# Clear empty set
set_1.clear()
print(set_1)
Run Code CopyOutput
{}
Summary
In this Python Set Tutorial, we learned how to use clear() method of Python set class to clear elements of a set, with the help of well detailed examples.