Lambda Calculus in Python

This tutorial 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).

Examples Lambda Calculus

Before I define lambda functions for you, let’s learn by example! Here are some interesting ones:

>>> f = lambda x, y: x + y
>>> f(1, 2)
>>> f(2, 3)

You define a lambda function that takes two input arguments x and y, and returns the sum x + y.

For example, you can use it to pass a function into a function:

>>> customers = ['Alice', 'Bob', 'Carl']
>>> ids = map(lambda name: name[:1], customers)
>>> list(ids)
['A', 'B', 'C']

The list customers consists of three strings. You define a map() function that applies the first function argument (functions are objects!) to each element in the list. The passed lambda function returns the first character of a string using a basic slicing operation.

Lambda Calculus is Turing Complete

The lambda function is Turing complete which means you can perform all computations a computer can perform—using only lambda functions! You can find more about the lambda calculus’ formal theory here.

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.

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

f = make_incrementor(42)

In the code snippet, 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.

You can solve this puzzle in our interactive puzzle app

Lambda Function Python Puzzle

Click the link and test your skills now!

Related Video: Lambda Functions

Leave a Comment

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