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

bonono at gmail.com bonono at gmail.com
Thu Nov 10 16:51:38 CET 2005

Alex Martelli wrote:
> 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.
No. my predicate sometimes is not function but inline expression that
needs scoping within nested for.

> 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.
That is one opinion and I think I can decide when to break or not to
break. Sometimes, breaking them in mutiple level for with interim name
assignment is not desirable. In fact, because python allows me to write
in both style, I practiced to write the same thing in both style and
found that the nested list expression way is less error prone(at least
for me ).

More information about the Python-list mailing list