[Tutor] list comprehension, efficiency?

bob gailer bgailer at gmail.com
Sun Oct 3 15:22:37 CEST 2010


  On 10/2/2010 8:02 PM, Steven D'Aprano wrote:
> 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.

Thank you. I needed that!
> 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.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC



More information about the Tutor mailing list