[ x for x in xrange(10) when p(x) ]

Bengt Richter bokr at oz.net
Thu Nov 10 17:01:29 EST 2005


On 10 Nov 2005 04:56:34 -0800, "bonono at gmail.com" <bonono at gmail.com> wrote:

>
>Peter Hansen wrote:
>> (I say "readable or somehow better" since you stated in another post "I
>> just try to use list/generator expression when possible" but you didn't
>> explain your reason for doing so.  I assume you have some reason other
>> than arbitrary whim.)
>The reason is simple:
>
>I found it easier to read for me and using list/generator expression
>helped me uncover a number of subtle bugs comparing with an imperative
>approach.
>
>on its own :
>
>takewhile(lambda x: condition(x), some_generator) is not very much
>difference than(well, still more things to type)
>
>(x for x in some_generator when condition(x))
I wish you wouldn't write "when" like that, as if it were legal python python syntax.
(Nor do I like guessing what it's supposed to mean ;-)

 >>> list (x for x in xrange(20) when x<5))
   File "<stdin>", line 1
     list (x for x in xrange(20) when x<5))
                                    ^
 SyntaxError: invalid syntax

If you want to terminate a generator expression after the first sequence of elements
satisfying a condition, and you don't want to use takewhile, I don't know of a gotcha
to prevent you from just raising StopIteration, using an expression that will do that, e.g.,

 >>> list (x for x in xrange(20) if x<5 or iter([]).next())
 [0, 1, 2, 3, 4]

Or a bit more readably:
 >>> def stop(): raise StopIteration
 ...
 >>> list (x for x in xrange(20) if x<5 or stop())
 [0, 1, 2, 3, 4]

IOW, your "when condition(x)" (IIUIC) can be spelled "if condition(x) or stop()"

>
>but when I have a number of them in the same expression, the
>takewhile/dropwhile becomes to add up.
If you don't like Alex'(s?) good advice, you can continue bracketed expressions
on several lines, and indent and group for clarity.

Regards,
Bengt Richter



More information about the Python-list mailing list