3

I have a simple question about lambda functions. I want to do a loop, in which every iteration defines a new lambda function based on a lambda function from the previous iteration.

f = lambda x: x**2
j=0
J=2
while j<J:
    f2 = lambda x: 0.5*f(x)
    f = f2
    j+=1

I expect the result of f(3) to be 2.25 = 0.5*0.5*3**2. However, I get the following error:

RecursionError: maximum recursion depth exceeded

I thought lambda functions can be used flexibly like this. I suppose there is a known pythonic way of how to do this properly?

2 Answers 2

4

The name f inside your lambda is looked up at the time the lambda is called - at which point it refers to the lambda itself, thus the infinite recursion.

The usual idiom for capturing a value at a particular moment in time is to make it a default parameter of the lambda, which gets evaluated at definition time:

    f2 = lambda x, f=f: 0.5*f(x)
Sign up to request clarification or add additional context in comments.

2 Comments

Is there also a way to do this using def rather than lambda?
Sure, the same trick with default parameters works just as well for a regular function. Keep in mind that lambdas do not add any actual new functionality to Python, they're just a shortcut for defining really simple functions.
3

When a lambda function is created, it maintains a reference to the local environment so that it can look up variables within the lambda when it is called. You need to pass in your first lambda function as a parameter to the second one:

f = lambda x: x**2
j=0
J=2
while j<J:
    f2 = lambda x, f=f: 0.5*f(x)
    f = f2
    j+=1

Note that this is covered in the Python docs FAQ.

2 Comments

Because the answers are exactly the same, I accepted the first one. Thank you
Is there also a way to do this using def rather than lambda?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.