Peter Otten __peter__ at
Fri Jun 1 12:14:02 CEST 2007

Sergey Dorofeev wrote:

> "Peter Otten" <__peter__ at> wrote in message
> news:f3oo0p$c7c$03$1 at
>>>>> 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)
>>>>> How to make x*x to be evaluated once?
>>>>>>> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5)
>>>>>>> +
>>>> cos(.5*.5)
>>>> True
>>>> The real answer is of course: Use a function.
>>> But what about something like
>>> lambda x: sin(y)+cos(y) where y=x*x
>>> ?
>>> May be this could be a PEP? If there is no straight way to do this.
>> def f(x):
>>    y = x*x
>>    return sin(y) + cos(y)
>> What is not straightforward about that?
> This code is needed once in a map, 

Perhaps you like [sin(y)+cos(y) for y in (x*x for x in items)] then.

> so I don't want 3+ extra lines. 

What syntax would you suggest for a lambda enhanced to cover your use case?
I suppose you will end up with roughly the same number of characters, all
crammed in one line -- or broken into lines at a random position as it
happens with overambitious list comprehensions.

> Solution seemed so simple...

It /is/ simple.

> I always considered python as languague, where simple things do not
> require extensive coding.

In Python, when conciseness and readability compete, readability tends to
win (with the inline if...else as a notable exception).

> Moreover, this construction is common thing in functional programming.

I can write Haskell in any language :-)


More information about the Python-list mailing list