Re: "For" loop and list comprehension similarity
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: "For" loop and list comprehension similarity

From: John Zenger <john_zenger@yahoo.com>
Date: Mon Mar 27 2006 - 01:15:42 CEST

Rather than a list comprehension, it would be faster and more
memory-efficient to use a generator comprehension. Just change the
square brackets to parentheses:

     for j in (i*2 for i in c if <test>):
        print j

Grant Edwards wrote:
> On 2006-03-26, s.lipnevich@gmail.com <s.lipnevich@gmail.com> wrote:
>
>>Hi All,
>>
>>I apologize if this was brought up before, I couldn't find any "prior
>>art" :-).
>>On more than one occasion, I found myself wanting to use a "conditional
>>loop" like this (with "Invalid syntax" error, of course):
>>
>> for i in c if <test>:
>> print i*2
>>
>>...because it's similar to the list comprehension construct:
>>
>> [i*2 for i in c if <test>]
>> ---------
>>
>>Is this the intended difference in constructs? The available equivalent
>>feels a bit awkward:
>>
>> for i in c:
>> if <test>:
>> print i*2
>
>
> for j in [i*2 for i in c if <test>]:
> print j
>
Received on Sun Apr 30 21:15:49 2006