Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readPython
#Python dictionaries#dict.clear()#in-place mutation#memory management
Flat illustration of a dictionary container being emptied of key-value cards, representing how Python dict clear() removes all entries in place.

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:

python
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.

python
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 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.

python
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:

python
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.

python
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:

python
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:

python
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 name d, and clear() removes every entry while keeping the object. The choice depends on what you need to remove.

ApproachWhat it removesObject identityTypical use
d.clear()All entriesPreservedReset shared state
d = {}The name's reference to the old dictReplacedDiscard old dict
d.pop(k)One entryPreservedRemove a single key
del dThe name dName removedDelete 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.

python
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:

python
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 tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.