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

Alex Martelli aleax at mail.comcast.net
Thu Nov 10 10:20:30 EST 2005


bonono at gmail.com <bonono at gmail.com> wrote:
   ...
> 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))

So use takewhile(condition, some_generator)

which is LESS to type.  When your predicate is a function, there's no
need to wrap a lambda around it, just like there's no need to wrap an
'[x for x in' or '(x for x in' around a list/iterator.


> but when I have a number of them in the same expression, the
> takewhile/dropwhile becomes to add up.

Complicated expressions often become hard to read; so, break the
expression up into more readable pieces, assigning names to the
intermediate steps.  There's negligible price to pay for that, since in
Python assignment is NOT a copy, just a 'naming' of an intermediate
object.  For example, instead of:

for x in takefile(foo, takewhile(bar, zlupp)): ...

you may choose to code, e.g.,

zlupps_bars = takewhile(bar, zlupp)
zb_foos = takewhile(foo, zlupps_bars)
for x in zb_foos: ...

Flat is better than nested.
Sparse is better than dense.
Readability counts.


Alex



More information about the Python-list mailing list