Python dictionary clear() method


Python tip:

You can use .clear to clear a dictionary.

Is it the same as foo = {} ?

No.

  1. foo = {} will create a new instance but other references will still point to the old items.
  2. Because of #1, foo = {} is probably faster than foo.clear()
  3. foo.clear() is slower but safer. Be careful with scope with foo = {}.

An example👇

user = {"name": "Jan", "username": "giaco"}

user.clear()
print(user). # => {}