"For" loop and list comprehension similarity
Mitja Trampus
nun at example.com
Sun Mar 26 13:38:44 EST 2006
s.lipnevich at 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
More information about the Python-list
mailing list