"For" loop and list comprehension similarity

Grant Edwards grante at visi.com
Sun Mar 26 16:19:18 EST 2006


On 2006-03-26, s.lipnevich at gmail.com <s.lipnevich at 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

-- 
Grant Edwards                   grante             Yow!  .. I wonder if I
                                  at               ought to tell them about my
                               visi.com            PREVIOUS LIFE as a COMPLETE
                                                   STRANGER?



More information about the Python-list mailing list