Lambda Functions in Python

What is the output of this code snippet?

 

def make_incrementor(n):
    return lambda x: x + n

f = make_incrementor(42)
print(f(0))
print(f(1))

 

This puzzle introduces an advanced language feature: lambda functions. Lambda functions are rooted in the mathematical area of lambda calculus. One of the pioneers of this area was Alonzo Church. He introduced lambda functions in 1936 even before the appearance of the first computers.

Lambda functions exist in a wide range of languages for functional programming. They are not only at the heart of functional programming languages, they are also the basis of many advanced Python language features. For example, the modern language Scala for parallel programming combines traditional language elements (e.g. from Java) with functional elements (e.g. lambda functions).
So how do lambda functions work?

A lambda function is an anonymous function without identifier. After the lambda keyword, the function takes one or more arbitrary arguments. The arguments are comma-separated and finished by a colon. After the colon follows a single expression. Yet, this expression can consist of complex calculations using the specified argument variables.
The lambda function then returns the result of this expression.
Hence, lambda functions are syntactical shortcuts for a subclass of normal Python functions.

In the puzzle, the function make_incrementor creates a lambda function at runtime. The created lambda function increases an element x by a fixed value n. For example, the incrementor function in the puzzle increments a value by 42. We assign this function to the variable f. Then we print the results when incrementing the values 0 and 1 by the incrementor 42.


Are you a master coder?
Test your skills now!

Related Video

Solution

42
43

 

Leave a Comment

Your email address will not be published. Required fields are marked *