0

For the following code:

def twice(f):
    return lambda x: f(f(x))

print(twice(twice(twice(lambda x: x+5)))(2))

The answer is 42, but it has no worked solutions. I would appreciate a detailed answer with explanation for this lambda expression and steps to build on my foundation.

1 Answers1

2

The lambda keyword in python creates a function, just like def.

def add_ten(x):
    return x + 10

add_ten = lambda x: x + 10

The two are equivalent*, and are both called in the same way now. The power of lambdas come in the ability to return functions. This is what your example is doing.

twice takes in a function, and returns a function that calls the original function twice, the second time with the result of the first call. The function twice returns takes one argument (that’s why you see the x in the lambda expression).

You might want to draw this out on paper at this point, as the last line just calls this function producing function over and over.

For learning more, try reading into lambda expressions in python. Python includes builtins map, reduce, and filter** that are commonly used with lambda expressions. Check these out for things you can accomplish more elegantly with lambdas. For more general ideas, read about functional programming.

*equivalent: it is however, not pythonic to use them as I did in this example. They should instead be used as anonymous functions (functions without a name), as they are in your example.

** and a host of others. I gave these as examples of builtins that take functions as arguments.

SamudNeb
  • 211
  • 2
  • 6
  • 1
    Good explanation, but lambda expressions don't let you accomplish anything that you couldn't without them except make an anonymous function. For example, `map`, `filter` and `reduce` don't *work with lambdas*, they work with *any function*, whether that is a function created by a lambda expression or by a function definition statement or a built-in function, it doesn't matter – juanpa.arrivillaga Sep 28 '20 at 03:21
  • Lambdas and regular functions aren't quite equivalent. Lambdas are meant to be exclusively anonymous, so [naming them is bad practice](https://stackoverflow.com/a/38381663/4518341), and [they're not easy to document](https://stackoverflow.com/q/50370917/4518341). The only advantage is that they can be used anonymously. – wjandrea Sep 28 '20 at 04:14
  • 1
    @wjandrea i was mainly trying to provide a simple example, not a useful example. I edited to allude to this, now, thanks! I didn’t actually realize that it wasn’t pythonic. – SamudNeb Sep 28 '20 at 04:35