Lee Lee - 3 months ago 7
Python Question

What's the difference between clear a dict and reassign an empty dict in python?

As for a dict

d
, what's the difference between

d.clear()


and

d = {}


both of which make
d
equal to
{}
.

=======

I have a dict mapping storing thousand large
ndarray
, like
{'key': ndarray, ...}
, occupying ~5GB memory. The mapping is updated each time in a nested loop. So my concern is mainly about the efficiency and memory release.

Answer

In second case you are creating a new object, and garbage collector will do the rest of job when its turn come. But in first one you are simply clearing the current object which is more proper way.

>>> d = {1:3}
>>> id(d)
139945829816032
>>> d.clear()
>>> d
{}
>>> id(d)
139945829816032
>>> 
>>> d = {}
>>> 
>>> id(d)
139945829816312