subexpressions

Steven Bethard steven.bethard at gmail.com
Fri Jun 1 15:02:54 EDT 2007


Sergey Dorofeev wrote:
> Please help, is there way to use sub-expressions in lambda?
> For example, if I want to calculate sin(x^2)+cos(x^2) I must code:
> lambda x: sin(x*x)+cos(x*x)
[and later]
> This code is needed once in a map, 

Peter Otten wrote:
> Perhaps you like [sin(y)+cos(y) for y in (x*x for x in items)] then.

Just wanted to emphasize this suggestion so that it doesn't get lost in 
the flood of lambda recommendations. If your code really looks like::

     map(lambda x: sin(x * x) + cos(x * x), items)

you should be using a list comprehension instead. Using map() here is 
not only more obscure and more verbose, but slower than::

     [sin(x * x) + cos(x * x) for x in items]

 From there, it's a simple nested generator comprehension to pull out 
the subexpression:

     [sin(y) + cos(y) for y in (x * x for x in items)]

If you aren't yet familiar with list and generator comprehensions, you 
should take a few minutes to look at some of your uses of map() and 
filter and see if you can simplify them using comprehensions instead.

STeVe



More information about the Python-list mailing list