Dictionary Methods
clear()
Remove all items from the dictionary.
dict.clear()
dict.clear() removes every key-value pair from the dictionary, leaving it completely empty.
This mutation happens in place, affecting all variables that reference the same dictionary object.
Result
Returns
None, the dictionary is emptied in place.
Run it
Try it
Run it and change it
user = {"id": 101, "name": "Sarah", "role": "admin"}
user.clear()
print("Dictionary contents:", user)
print("Length:", len(user)) Output
Press Run to see what it prints.Worth knowing
- In-place clearing vs reassigning: Reassigning
user = {}creates a new empty dict, but other references to the original dictionary remain unchanged. Callinguser.clear()clears the dictionary for all references.