Python dictionary clear() method
Python tip:
You can use
.clear
to clear a dictionary.Is it the same as
foo = {}
?No.
foo = {}
will create a new instance but other references will still point to the old items.- Because of #1,
foo = {}
is probably faster thanfoo.clear()
foo.clear()
is slower but safer. Be careful with scope withfoo = {}
.An example👇
user = {"name": "Jan", "username": "giaco"} user.clear() print(user). # => {}