We could as consistenly explain that the syntax
for n in range(10) if n%3==0:
body
means
for n in range(10):
if n%3==0:
body
This syntax has also the benefit of avoiding an extra level of
indentation (the one for the if) that bears no real meaning on a
structural level.
I'm sorry, I don't see what you mean about avoiding the extra level of
indentation? I can see a very real structural and logical distinction that
the if-block makes, and IMO it's a good thing that that needs to be set
apart.
On Tue, 25 Aug 2009 10:25:27 -0700, seb <sdemen...@gmail.com> wrote:
Tx Chris for your reply !
i am still a bit puzzle by the following.
I read in
http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators
"""Python 3.0 unifies all collection types by introducing dict and set
comprehensions, similar to list comprehensions:
[ n*n for n in range(5) ] # regular list comprehension
[0, 1, 4, 9, 16]
{ n*n for n in range(5) } # set comprehension
{0, 1, 4, 16, 9}
{ n: n*n for n in range(5) } # dict comprehension
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
"""
and we can add to this list the quite similar syntax for generator
expressions.
On all these loop constructs, one can consistenly add filtering on a
condition by adding an "if ..." after the "for ... in ..." part (and
it looks to me difficult to argue, for instance, that we should not
allow filtering for dict comprehesion because we could get the same
result by some other construct)
If the "if ..." part after the "for ... in ..." is so much used in all
these list/dict/set comprehensions and in the generator expressions,
it makes sense to me to have it also for the "for as a statement"
syntax :
[ n*n for n in range(10) if n%3 == 0]
{ n*n for n in range(10) if n%3 == 0}
{ n: n*n for n in range(10) if n%3 == 0}
( n*n for n in range(10) if n%3 == 0)
for n in range(10) if n%3 == 0:
print n*n
In fact, we often see the list comprehension [ n*n for n in range(10)
if n%3 == 0] explained as being equivalent to
l = []
for n in range(10):
if n%3 == 0:
l.append(n)
We could as consistenly explain that the syntax
for n in range(10) if n%3==0:
body
means
for n in range(10):
if n%3==0:
body
This syntax has also the benefit of avoiding an extra level of
indentation (the one for the if) that bears no real meaning on a
structural level.
Maybe a PEP could do the job...
Sébastien
--
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --
Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
--
http://mail.python.org/mailman/listinfo/python-list