[BangPypers] Are comprehensions faster?

Senthil Kumaran orsenthil at gmail.com
Mon Feb 9 14:36:57 CET 2009

On Mon, Feb 9, 2009 at 5:55 PM, Chetan Nichkawde
<chetan.nichkawde at gmail.com> wrote:
> Are comprehensions (list, dict, set) supposed to run faster than regular
> approach?

Thats quite an interesting question, which led me to do some research
and discussions/

Lets do some benchmarking:

# using list comprehension:

>>> import timeit
>>> timeit.Timer("[i for i in range(1000)]").timeit(number=1000)

 # What is the equivalent of the above in regular way? Frankly, you
wont find any. Either you will find use of methods or using functions
or lambdas.

# Lets use a regular function

>>> timeit.Timer("for i in range(1000): l.append(i)","l=[]").timeit(number=1000)

You see that is slow and the reason is  l.append being called again
and again. lets eliminate it.

>>> timeit.Timer("for i in range(1000): func(i)","l=[];func=l.append").timeit(number=1000)

# Lets use map do the operation.

>>> timeit.Timer("map(func,range(1000))","l=[];func=l.append").timeit(number=1000)

The Best Article I found explaining List Comprehension and performance is this:

Pay attention to the Optimization section.

The answer for your question is, "List Comprehension is faster than
regular way. when it is just that" but for all practical purposes
where some method lookups and assignments would be involved, it would
hardly matter in terms of speed for LC vs regular way. However, the
map, filter way of doing seems faster than List Comprehension.

But we got agree that List Comprehension is a neat way of doing things.


More information about the BangPypers mailing list