Is a list or dictionary faster in Python?

How important are these two performance indicators?

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

and

 tmp = {} tmp[0] = True print tmp[0] 
+3
python data-structures
source share
3 answers

The timeit module in the standard library is designed to answer such questions! Forget print (which will have an unpleasant side effect of material eruption on 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 ...! -)

+23
source share

Not only micro-optimization is usually pointless at all, I find it especially difficult and mysterious for Python in particular. It is very easy to make your code both slower and harder. See this stack overflow question for an example, where the simplest, clearest, and shortest Python solutions were also the fastest.

As other people with actual tests showed, the difference in speed between the two options is quite small. Less minor difference between semantics. Lists and dictionaries are not just two implementations of the same concept, but are intended for different purposes. Choose the one that suits you best.

+6
source share

they are fair in my testing

-2
source share

All Articles