Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.clear() method

Reference for Python set.clear(): remove every element from a set in place, how it differs from rebinding to set(), shared references and return value None.

The clear() method removes every element from a set. The set object itself survives and becomes empty, so everything that refers to it sees the change. The method returns None.

That "same object" detail is the reason to choose clear() over s = set(): the assignment creates a new set and leaves the old one untouched for other names.

Python
s = {1, 2, 3}
s.clear()
print(s)   # set()

Try it

Python Emptying a set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python clear() versus rebinding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
set.clear()
Name Description
(none) The method takes no arguments.

Return value: None.

Usage notes

  • It mutates in place. Every variable that points to the set sees it empty. Take a copy first with set.copy() if you still need the elements.
  • s = set() is different. It rebinds the name only. Use it when other references should keep their data.
  • Empty is falsy. After clear(), if s: is false and len(s) is 0.
  • Works on empty sets without error.
  • Not available on frozenset, which is immutable.
  • Same name on other types. list.clear() and dict.clear() behave the same way.