Scott Scott - 2 months ago 7
Python Question

Is a list or dictionary faster in Python?

How much of a difference are these two as far as performance?

tmp = []
tmp.append(True)
print tmp[0]


And

tmp = {}
tmp[0] = True
print tmp[0]

Answer

The timeit module in the standard library is designed just to answer such questions! Forget the print (which would have the nasty side effect of spewing stuff to your terminal;-) and compare:

$ python -mtimeit 'tmp=[]; tmp.append(True); x=tmp[0]'
1000000 loops, best of 3: 0.716 usec per loop
$ python -mtimeit 'tmp={}; tmp[0]=True; x=tmp[0]'
1000000 loops, best of 3: 0.515 usec per loop

So, the dict is the winner -- by 0.2 microseconds...!-)

Comments