views:

1276

answers:

3

In python, is there a difference between calling clear() and assigning {} to a dictionary? If yes, what is it? Example:

d = {"stuff":"things"}
d.clear()   #this way
d = {}      #vs this way

+27  A: 

If you have another variable also referring to the same dictionary, there is a big difference:

>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}

This is because assigning d = {} creates a new, empty dictionary and assigns it to the d variable. This leaves d2 pointing at the old dictionary with items still in it. However, d.clear() clears the same dictionary that d and d2 both point at.

Greg Hewgill
Thanks. This makes sense. I still have to get used to the mindset that = creates references in python...
Marcin
= copies references to names. There are no variables in python, only objects and names.
ΤΖΩΤΖΙΟΥ
While your "no variables" statement is pedantically true, it's not really helpful here. As long as the Python language documentation still talks about "variables", I'm still going to use the term: http://docs.python.org/reference/datamodel.html
Greg Hewgill
+9  A: 

d = {} will create a new instance for d but all other references will still point to the old contents. .clear() will reset the contents, but all references to the same instance will still be correct.

Michel
This is good answer too. +1 for best runner up :)
Marcin
+4  A: 

In addition to the differences mentioned in other answers, there also is a speed difference. d = {} is over twice as fast:

python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()"
10 loops, best of 3: 127 msec per loop

python -m timeit -s "d = {}" "for i in xrange(500000): d = {}"
10 loops, best of 3: 53.6 msec per loop
odano