"For" loop and list comprehension similarity

Ben Finney bignose+hates-spam at benfinney.id.au
Sun Mar 26 17:40:56 EST 2006


s.lipnevich at gmail.com writes:

> 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>]

Why not combine the two:

    for i in [j for j in c if <test>]:
        print i*2

-- 
 \       "I got food poisoning today. I don't know when I'll use it."  |
  `\                                                  -- Steven Wright |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list