Python Dict Clear: Syntax, Behavior, and Aliasing
python dict clear: Learn how dict.clear() removes all items from a Python dictionary in place, how it differs from reassignment, and when each approach is the right call.
To perform a python dict clear, call dict.clear() on the dictionary. The method removes every key-value pair in place and returns None. This is the standard way to empty a dictionary while keeping the same object alive, which matters when other variables, containers, or function callers still hold a reference to it.
Basic Syntax and Return Value
The syntax is minimal:
scores = {"alice": 10, "bob": 7} scores.clear() print(scores) # {}
clear() takes no arguments and always returns None. It does not return the emptied dictionary, so chaining like d.clear().update(...) fails with an AttributeError. If you need a fresh dictionary with new contents, assign a new literal instead.
What clear() Actually Removes
Calling clear() removes all entries and releases the references the dictionary holds to its keys and values. The dictionary object itself remains the same object; only its contents are gone.
d = {"a": 1, "b": 2} before = id(d) d.clear() after = id(d) print(before == after) # True
The identity check confirms that no new object was created. This is the defining difference between clear() and rebinding the name to a new dictionary.
clear() vs Reassigning a New Dictionary
The most common confusion is between d.clear() and d = {}. Both leave the name d referring to an empty dictionary, but the underlying behavior is different.
original = {"a": 1} alias = original original.clear() print(alias) # {}
Because clear() mutates the object in place, alias — which references the same object — also becomes empty. Reassignment does not behave this way:
original = {"a": 1} alias = original original = {} print(alias) # {'a': 1}
Here original now points to a brand-new empty dictionary, while alias still references the original object with its data intact.
Choose clear() when the dictionary object must remain the same instance: shared caches, objects that store the dictionary as an attribute, or default mutable arguments that other code depends on. Choose reassignment when you want to drop the old dictionary entirely and no other reference to it matters.
How clear() Affects Shared References
The in-place behavior is especially visible when a dictionary is passed to a function.
cache = {"user": "alice", "session": "s-123"} def reset(store): store.clear() reset(cache) print(cache) # {}
The function clears the caller's dictionary because store and cache refer to the same object. If the function instead rebinds store = {}, the caller's dictionary is untouched. This distinction is a common source of subtle bugs when refactoring code that resets state.
The same applies to dictionaries stored inside other structures:
state = {"count": 5} registry = {"main": state} state.clear() print(registry) # {'main': {}}
Clearing state also empties the dictionary reachable through registry["main"], because both names reference the same object.
Performance and Memory Behavior
clear() is O(n) in the number of entries: it must visit each key and value to decrement its reference count. For a dictionary with a large number of entries, this work is unavoidable regardless of whether you use clear() or let the dictionary be garbage collected.
Reassignment has a subtler cost profile. Rebinding d = {} is O(1) for the name itself, but the old dictionary is deallocated when its reference count drops to zero, which is again O(n) to release all entries. If other references to the old dictionary exist, deallocation is deferred and the memory stays allocated until those references disappear.
The practical difference is about object lifetime, not raw speed. clear() immediately releases the references to keys and values, allowing their memory to be reclaimed even while the dictionary object stays alive. This is useful when a long-lived dictionary temporarily holds large objects that should be freed:
def process_batch(batch): buffer = {} for item in batch: buffer[item.id] = item.payload # ... use buffer ... buffer.clear() # release references to payloads early
No benchmark numbers are needed here; the mechanism is what matters. If the dictionary is small or short-lived, either approach is fine. If the dictionary is large and lives for a long time, clear() gives you explicit control over when the references are released.
When to Use clear() Instead of pop() or del
pop() removes a single key, del d removes the variable name itself, and clear() removes every entry while keeping the object. The choice depends on what you need to remove.
| Approach | What it removes | Object identity | Typical use |
|---|---|---|---|
d.clear() | All entries | Preserved | Reset shared state |
d = {} | All entries (new object) | Replaced | Discard old dict |
d.pop(k) | One entry | Preserved | Remove a single key |
del d | The variable | Name removed | Delete the reference |
Use pop() when you need the removed value or only one key. Use clear() when you want to reset an entire dictionary without losing the object. Use reassignment when nothing else references the old dictionary and you want a fresh start.
Common Pitfalls: Iteration and Edge Cases
Modifying a dictionary while iterating over it is not supported. Clearing inside a loop over the same dictionary may raise RuntimeError: dictionary changed size during iteration in CPython, or may silently skip entries.
d = {"a": 1, "b": 2, "c": 3} for key in d: d.clear() # may raise RuntimeError
If you need to clear a dictionary after processing its contents, iterate over a copy of the keys first, or collect the keys and clear afterward:
for key in list(d): del d[key]
Calling clear() on an already empty dictionary is a harmless no-op. Subclasses of dict inherit clear() unless they override it; if you implement a custom mapping, you must provide your own clear() method to satisfy the MutableMapping interface. When you override clear() in a subclass, call super().clear() if you still want the standard behavior, or implement the removal logic explicitly.