Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python dict.clear() method

Reference for Python dict.clear(): remove every item from a dictionary in place, how it differs from rebinding to {}, and what happens to views and aliases.

The dict.clear() method removes every key-value pair from a dictionary. The dictionary object itself survives and is simply empty afterwards. It returns None.

Because the object is emptied in place, every other name that refers to the same dictionary sees the change. That is the key difference from d = {}, which only makes the name d point to a new empty dictionary and leaves the old one untouched.

Python
config = {"debug": True, "port": 8000}
config.clear()
print(config)   # {}

Try it

Python Clearing a dictionary

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
dict.clear()

clear() takes no arguments.

Return value: None.

Raises: nothing, even if the dictionary is already empty.

Usage notes

  • In place. All references to the same dictionary see it become empty. Use d = {} when you want other references to keep the old contents.
  • Views stay live. Views from keys(), values() and items() are not invalidated by clear(); they just become empty.
  • Values are released. The dictionary drops its references, so objects with no other references can be garbage-collected. Nested objects that are used elsewhere are not destroyed.
  • Do not call it while iterating over the same dictionary. Changing its size during a for loop raises RuntimeError: dictionary changed size during iteration.
  • Reusing a dict as a cache that you reset is a good use for clear(): the object identity stays stable for the code that holds it.
  • Related types: list.clear() and set.clear() do the same thing. A collections.defaultdict or OrderedDict has the same method.
  • Deleting one key is done with del d[key] or dict.pop().