Scott Scott - 9 months ago 63
Python Question

Is a list or dictionary faster in Python?

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

tmp = []
print tmp[0]


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


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...!-)