set.clear()
Empties a set in place, leaving set(). Every variable that refers to the same set sees it empty afterwards.
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
Python
ids = {4, 5, 6}
ids.clear()
print(ids)
print(len(ids))Output
set() 0
2clear() vs a new set
Python
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
Python
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.
Python
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.
Related
set.pop()Removes one element from a set and returns it. You cannot choose which: sets have no order, so treat it as arbitrary.set.remove()Deletes an element from a set. Raises KeyError if the element is not in the set; use discard() to skip that check.set.discard()Removes an element from a set if it is there, and silently does nothing if it is not. It never raises an error.list.clear()Empties a list in place, so the same list object ends up with no items. Every variable pointing to it sees the change.dict.clear()Deletes every key and value from a dictionary in place. Every variable that refers to the same dictionary sees it empty.