mutation

dict.clear

Removes all items from the dictionary in place, leaving it empty. Returns None.

d.clear()

Parameters

Parameter Purpose
(no parameters) clear takes no arguments
returns None — mutates the dict in place

Examples

>>> d = {'a': 1, 'b': 2}
>>> d.clear()
>>> d
{}

Empties the dict — same identity, zero entries

>>> d = {'a': 1}
>>> ref = d
>>> d.clear()
>>> ref
{}

All aliases see the change because it mutates in place

>>> d = {'a': 1}
>>> print(d.clear())
None

Returns None, not the dict

>>> d = {'a': 1}
>>> d = {}
>>> # vs. d.clear() — assignment rebinds, clear() empties the SAME object

d = {} creates a new object; d.clear() keeps identity

Gotcha

d = {} rebinds the name (other references keep the old data); d.clear() empties the shared object so all aliases see it. Cannot be undone.

Related methods

← All Python dict methods · String methods · Built-in functions