conditional for-statement

Piet van Oostrum piet at cs.uu.nl
Tue Aug 25 17:57:21 EDT 2009


>>>>> seb <sdementen at gmail.com> (s) wrote:

>s> i am still a bit puzzle by the following.

>s> I read in http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators

>s> """Python 3.0 unifies all collection types by introducing dict and set
>s> comprehensions, similar to list comprehensions:

>>>>> [ n*n for n in range(5) ] # regular list comprehension
>s> [0, 1, 4, 9, 16]
>>>>> 
>>>>> { n*n for n in range(5) } # set comprehension
>s> {0, 1, 4, 16, 9}
>>>>> 
>>>>> { n: n*n for n in range(5) } # dict comprehension
>s> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>s> """
>s> and we can add to this list the quite similar syntax for generator
>s> expressions.

>s> On all these loop constructs, one can consistenly add filtering on a
>s> condition by adding an "if ..." after the "for ... in ..." part (and
>s> it looks to me difficult to argue, for instance, that we should not
>s> allow filtering for dict comprehesion because we could get the same
>s> result by some other construct)

You can also say:
[x+y for x in range(3) for y in range(4) if x < y]
If you want to write this as a loop you have to put the for's on
separate lines separated by colons, so why not the if also? Or would you
also like to have the for's on one line?
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list