NEWBIE: Extending a For Statement.

Dustan DustanGroups at gmail.com
Mon May 21 08:53:48 EDT 2007


On May 21, 7:22 am, Jean-Paul Calderone <exar... at divmod.com> wrote:
> On 21 May 2007 05:10:46 -0700, mosscliffe <mcl.off... at googlemail.com> wrote:
>
>
>
> >I keep seeing examples of statements where it seems conditionals are
> >appended to a for statement, but I do not understand them.
>
> >I would like to use one in the following scenario.
>
> >I have a dictionary of
>
> >mydict = { 1: 500, 2:700, 3: 800, 60: 456, 62: 543, 58: 6789}
>
> >for key in mydict:
> >     if key in xrange (60,69) or key == 3:
> >           print key,mydict[key]
>
> >I would like to have the 'if' statement as part of the 'for'
> >statement.
>
> >I realise it is purely cosmetic, but it would help me understand
> >python syntax a little better.
>
> Only list comprehensions and generator expressions support this extension
> to the loop syntax.
>
> [key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3]
> (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3]

ack!
>>> (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3]
  File "<stdin>", line 1
    (key, mydict[key] for key in mydict if key in xrange(60, 69) or
key == 3]
                        ^
SyntaxError: invalid syntax

Perhaps you meant that second one to be:
(key, mydict[key] for key in mydict if key in xrange(60, 69) or key ==
3)

> For the statement form of 'for', there is no syntactic way to combine it
> with 'if' into a single statement.

There is a dumb hack to get it to happen, but I'm not going to it
here, because Guido never meant for generator expressions to be used
that way. To the OP: I would suggest you just live what might seem
like excess indentation; it's good for your eyes.

> Jean-Paul




More information about the Python-list mailing list