Skip to main content

Python Set clear() Function

The Set clear() method clear() method removes all items from the set, making it an empty set.

Syntax

my_set.clear()

clear() Parameters

Python Set clear() function does not take any parameters.

clear() Return Value

Python Set clear() function does not return any value: it empties the set in place.

Examples

Example 1: Empty a Set with clear()

For example, let's

my_set = {'Tom', 'David', 'Anna'}
my_set.clear()

print(my_set) # Output: set()

output

set()

Example 2: Clearing a set of numbers

# set of prime numbers
primeNumbers = {2, 3, 5, 7, 11}
primeNumbers.clear()

print(primeNumbers) # Output: set()

output

set()

Example 3: clear() vs Assigning an Empty Set

clear() is not same as assigning an empty set my_set = {}.

Assigning an empty set to my_set with my_set = {} does not clear the set in-place because it essentially replaces the my_set variable with a new, empty set. This means that if there were other references to the original set, those references remain unchanged, potentially leading to issues.

In the following example you can see an example of assigning a new empty set instead of clearing with clear() method:

# Original set
original_set = {1, 2, 3}

# Another reference to the original set
another_reference = original_set

# Attempt to clear the set using assignment
original_set = {}

# Print the original set and the other reference
print("Original set after clearing:", original_set)
print("Another reference after clearing:", another_reference)

output

Original set after clearing: {}
Another reference after clearing: {1, 2, 3}