Python Set clear() method



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.

Syntax

Following is the syntax and parameters of Python Set clear() method.

Open Compiler
set_name.clear()

Parameter

This method does not take any parameters.

Return value

This method This function returns an empty set.

Example 1

Following is the example of the clear() method which clears the given set and prints the empty set −

Open Compiler
# 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 −

Open Compiler
# 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.

Open Compiler
# 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.

Open Compiler
# Creating a set cities = {'New York', 'London', 'Paris'} # Conditional clearing if len(cities) > 2: cities.clear() print(cities)

Output

set()
python_set_methods.htm
Advertisements