clear() deletes every key/value pair, leaving an empty dict {}. The dict object itself survives, so the change is in place.
Any other variable, list, or dict that refers to the same object sees the empty dict too. That is the key difference from writing d = {}, which only points one name at a new dict.
dict.clear() is an instance method of the built-in dict type: call it on a dictionary with dot notation, such as cart.clear(...). No import is needed.
Syntax
Call it with no arguments; there is nothing useful to store from the result.
python
d.clear()
Call
What it does
cart.clear()
Empties cart; every name bound to the same dict now sees {}.
{"a": 1, "b": 2}.clear()
Returns None; the dict becomes {}.
cart = {}
Not the same: binds the name to a new dict, and other references keep the old items.
del d is different again: it deletes the named, not the items, and the dict lives on if something else refers to it.
Method signatures
python
dict.clear()
# returns: None; the dict is now empty
Parameters
clear() takes no parameters.
Return Value
Return Value
Description
None
Always None. The same dict object is now empty.
Python Examples
Example 1 — Empty a Shopping Cart After Checkout
Count the items, clear the cart, and check a second name that refers to the same dict.
Tuple keys. Each cache entry is keyed by the hashable tuple (amount, currency).
First call computes. 10 times 0.5 is 5.0, stored as the cache's single entry.
Stale hit. After the rate drops to 0.25, the cached 5.0 is still returned, because the key has not changed.
Clear to refresh.cache.clear() empties the same dict the function uses, so the next call recomputes 2.5 and stores it again.
Frequently Asked Questions
None. It empties the dict in place, so there is nothing to assign.
d.clear() empties the existing object, so every reference to it sees an empty dict. d = {} only makes the name d point to a new dict; other references keep the old items.
No. The dict object still exists and is simply empty. del d removes the name d instead.
Copy it first with backup = d.copy(), then call d.clear(). The backup keeps the old items.
Not on the dict you are looping over: the size change raises RuntimeError on the next loop step. Clear it after the loop ends.