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
dict.pop
Removes the specified key and returns its value. If the key is missing, returns default if provided; otherwise raises KeyError.
dict.popitem
Removes and returns the last inserted (key, value) pair as a 2-tuple in LIFO order. Raises KeyError if the dictionary is empty.
dict.copy
Returns a shallow copy of the dictionary — a new dict object with the same key-value pairs. Values themselves are not copied, so nested mutable objects are still shared between the original and the copy.
dict.update
Updates the dictionary in place with key/value pairs from other, overwriting existing keys. Accepts another mapping, an iterable of key/value pairs, and/or keyword arguments; returns None.
dict[key] = value
Assigns value to key using bracket subscription syntax, invoking __setitem__ under the hood. Creates the entry if key is absent, or overwrites the existing value; preserves the original insertion order when the key already exists.
← All Python dict methods · String methods · Built-in functions