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.