Python Reference ยท Dictionaries and Sets
Python dict.clear() method
Reference for Python dict.clear(): remove every item from a dictionary in place, how it differs from rebinding to {}, and what happens to views and aliases.
The dict.clear() method removes every key-value pair from a dictionary. The dictionary object itself survives and is simply empty afterwards. It returns None.
Because the object is emptied in place, every other name that refers to the same dictionary sees the change. That is the key difference from d = {}, which only makes the name d point to a new empty dictionary and leaves the old one untouched.
config = {"debug": True, "port": 8000} config.clear() print(config) # {}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
dict.clear()
clear() takes no arguments.
Return value: None.
Raises: nothing, even if the dictionary is already empty.
Usage notes
- In place. All references to the same dictionary see it become empty. Use
d = {}when you want other references to keep the old contents. - Views stay live. Views from
keys(),values()anditems()are not invalidated byclear(); they just become empty. - Values are released. The dictionary drops its references, so objects with no other references can be garbage-collected. Nested objects that are used elsewhere are not destroyed.
- Do not call it while iterating over the same dictionary. Changing its size during a
forloop raisesRuntimeError: dictionary changed size during iteration. - Reusing a dict as a cache that you reset is a good use for
clear(): the object identity stays stable for the code that holds it. - Related types:
list.clear()andset.clear()do the same thing. Acollections.defaultdictorOrderedDicthas the same method. - Deleting one key is done with
del d[key]ordict.pop().
Related
dict,dict.copy(),dict.pop(),list.clear(),set.clear()- Lessons: Dictionaries, Dictionary methods