Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 344
Scott Avatar asked Jun 03 '09 03:06

Scott


People also ask

What is faster dictionary or list?

It is more efficient to use dictionaries for the lookup of elements as it is faster than a list and takes less time to traverse. Moreover, lists keep the order of the elements while dictionary does not. So, it is wise to use a list data structure when you are concerned with the order of the data elements.

Why is Dict faster than list?

The reason is because a dictionary is a lookup, while a list is an iteration. Dictionary uses a hash lookup, while your list requires walking through the list until it finds the result from beginning to the result each time.

Which is faster list or tuple or dictionary in Python?

It is well-known that in Python tuples are faster than lists, and dicts are faster than objects.

Which is more memory efficient list or dictionary?

Dictionary occupies much more space than a list of tuples. Even an empty dict occupies much space as compared to a list of tuples. Example 1: As we can clearly see that there is a huge difference between memory consumption of both the datatypes when both are empty.


2 Answers

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.

like image 38
John Y Avatar answered Oct 04 '22 00:10

John Y


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

like image 69
Alex Martelli Avatar answered Oct 03 '22 23:10

Alex Martelli