Python Dict Clear: Syntax, Behavior, and Aliasing
Learn how `dict.clear()` removes all items from a Python dictionary in place, why it matters for aliases and shared state, and when reassignment is the better choice.

To clear a Python dictionary in place, 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) # TrueThe 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 Reassignment
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 mutable defaults 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
In CPython, clear() is O(n) in the number of entries: it must visit each key and value to release its reference. For a dictionary with a large number of entries, this work is eventually required regardless of whether you use clear() or let the dictionary be garbage collected. The Python language specification does not guarantee a particular complexity, so treat this as an implementation detail.
Reassignment has a subtler cost profile. Rebinding d = {} is O(1) for the name itself, but if nothing else references the old dictionary, its entries must eventually be released — again O(n) in CPython. 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. In CPython, 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 earlyNo 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 name d, 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 = {} | The name's reference to the old dict | Replaced | Discard old dict |
d.pop(k) | One entry | Preserved | Remove a single key |
del d | The name d | 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 RuntimeErrorIf 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 by subclassing collections.abc.MutableMapping, the mixin provides a clear() based on popitem(), so you do not have to write one; you may override it when you need a more direct implementation. When you override clear() in a dict subclass, call super().clear() if you still want the standard behavior, or implement the removal logic explicitly.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.