[Tutor] list comprehension, efficiency?

Steven D'Aprano steve at pearwood.info
Sun Oct 3 02:02:09 CEST 2010

On Sun, 3 Oct 2010 01:17:39 am bob gailer wrote:

> I ran dis on a for loop and the equivalent comprehension.
> I was surprised to see almost identical code.
> I had assumed (and now wish for) that a comprehension would be a
> primitive written in C and thus much faster!

How could it be? A list comp is syntactic sugar. It needs to perform the 
same steps as a for-loop, and call an arbitrary Python expression. It's 
not like map() that takes a function object. Unless you had a separate 
primitive for every imaginable Python expression -- which is 
impossible -- list comps need to generate relatively similar code to 
for-loops because they do relatively similar things.

Besides, in recent versions of Python the speed of for-loops is quite 
good. The bottleneck is rarely the loop itself, but the work you do in 
the loop or the size of the loop.

Steven D'Aprano

More information about the Tutor mailing list