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: Mitja Trampus <nun@example.com>
Date: Sun Mar 26 2006 - 20:38:44 CEST

s.lipnevich@gmail.com wrote:

> 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

Maybe there's been a PEP, don't really know...
Currently, the only sensible alternative is what you've written below:

> The available equivalent
> feels a bit awkward:
>
> for i in c:
> if <test>:
> print i*2

This indeed doesn't look nice, especially if you've got lots of code instead of just
print. An alternative which avoids double indentation is

for i in c:
        if not <test>: continue
        print i*2
Received on Sun Apr 30 21:14:28 2006