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
set.pop
Removes and returns an arbitrary element from the set. Raises KeyError if the set is empty.
set.remove
Removes the specified element from the set. Raises KeyError if the element is not present.
set.add
Adds a single hashable element to the set in place. If the element is already present, the set is unchanged (no error).
set.discard
Removes an element from the set if it is present, and does nothing otherwise. Unlike remove(), never raises an error.
set.update
Adds every element from each iterable argument to s in place. Equivalent to a union but mutates s instead of returning a new set.
← All Python set methods · List methods · list vs tuple vs set