add-remove

set.clear

Removes all elements from the set, leaving it empty. Mutates the set in place; other references to the same set see it emptied.

s.clear()

Parameters

Parameter Purpose
(no args) clear() takes no arguments
returns None — mutates in place

Examples

>>> s = {1, 2, 3}
>>> s.clear()
>>> s
set()

All elements removed.

>>> s = set()
>>> s.clear()
>>> s
set()

No error on an already-empty set.

>>> a = {1, 2}
>>> b = a
>>> a.clear()
>>> b
set()

b is the same object, so it is also empty.

>>> a = {1, 2}
>>> a = set()
>>> a
set()

Rebinding creates a new empty set — the old set is untouched.

Gotcha

clear() mutates — every reference to that set sees the change. To leave the old set alone, rebind the name to set() instead.

Related methods

← All Python set methods · List methods · list vs tuple vs set