The Python Set clear() method is used to remove all elements from a set effectively making it an empty set. This method does not take any arguments and modifies the set in place. It is particularly useful when we want to reuse an existing set without retaining its previous elements.
SyntaxFollowing is the syntax and parameters of Python Set clear() method.
set_name.clear()Parameter
This method does not take any parameters.
Return valueThis method This function returns an empty set.
Example 1Following is the example of the clear() method which clears the given set and prints the empty set −
# initialzing a set number_set = {1, 2, 3, 4, 5} # clearing the set number_set.clear() # printing the set print(number_set)Output
set()Example 2
In below example we are creating a set by adding elements into it and later on we used the clear() function to clear the set −
# Creating a set numbers = {1, 2, 3, 4, 5} # Adding more elements numbers.update([6, 7, 8]) print(numbers) # Clearing the set numbers.clear() print(numbers)Output
{1, 2, 3, 4, 5, 6, 7, 8} set()Example 3
Now, in here we are using the clear() method in a loop for clearing the elements of the set.
# Creating a list of sets list_of_sets = [{1, 2}, {3, 4}, {5, 6}] # Clearing each set in the list for s in list_of_sets: s.clear() print(list_of_sets)Output
[set(), set(), set()]Example 4
We can clear the elements in the set based on the given condition and here is the example which clears the set based on the condition where the length of the cities is greater than 2.
# Creating a set cities = {'New York', 'London', 'Paris'} # Conditional clearing if len(cities) > 2: cities.clear() print(cities)Output
set()
python_set_methods.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4