Set method

set.clear()

Empties a set in place, leaving set(). Every variable that refers to the same set sees it empty afterwards.

BeginnerEvery example below runs in your browser. Change the code and press Run.

set.clear()

clear() removes every element from a set. The set itself stays, now empty.

An empty set prints as set(), not {}, because {} means an empty dictionary in Python.

As with lists and dictionaries, s.clear() empties the one shared set, while s = set() just points the name s at a new empty set and leaves anyone else holding the old one unaffected.

Return value

Nothing (None). The set is changed in place.

Examples

1Empty a set

Pythoneditable
ids = {4, 5, 6}
ids.clear()
print(ids)
print(len(ids))
Output
set()
0

2clear() vs a new set

Pythoneditable
a = {1, 2}
alias = a
a.clear()
print(alias)
b = {1, 2}
other = b
b = set()
print(other)
Output
set()
{1, 2}

3Reset what was seen each day

Pythoneditable
days = [["ana", "ben", "ana"], ["ben"]]
seen = set()
for n, visits in enumerate(days, start=1):
    seen.clear()
    for v in visits:
        seen.add(v)
    print("Day", n, "unique:", len(seen))
Output
Day 1 unique: 2
Day 2 unique: 1

Common mistakes

Checking for an empty set with == {}

{} is an empty dictionary, so s == {} is always False for a set. Use not s or len(s) == 0.

Pythoneditable
s = set()
print(s == {})
print(not s)
Output
False
True

Questions people ask

How do I empty a set in Python?

s.clear(), or s = set() if nothing else refers to the same set.

How do I make an empty set?

set(). Writing {} creates an empty dictionary.

Spotted a mistake on this page? Tell us