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]
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]
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...!-)
Of course there will be a slight difference, but honestly you shouldn't be worrying about this. What you're doing is micro-optimizing your code, which is something you should avoid. In essence, you're wasting time optimizing something that won't make any difference in your application at all, when you could be spending that time doing something worthwhile.
So is there a difference in speed between the two examples you posted? Certainly. Is it going to matter? Nope. :)
Not only is micro-optimization usually pointless in general, I find it is especially difficult and arcane for Python in particular. It is very easy to actually make your code simultaneously slower and more complicated. See this Stack Overflow question for an example where the simplest, clearest, and shortest Python solutions also turned out to be the fastest.
As others have shown with actual tests, the speed difference between your two choices is quite small. What is less small is the semantic difference. Lists and dictionaries are not merely two implementations of the same concept, but are intended for different uses. Pick the one which better fits your use.