This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Lambda functions

Lambda functions, simply put, are functions with no name. They are also known as annoymous functions.

So, instead of writing something like this:

def add(x, y , z):
    return x + y + z

print(add(1, 2, 3))

You can do something like this.

add = lambda x, y, z: x+y+z
print(add(1, 2, 3)

Lambda functions can have any number of arguments, but only one expression in its body.

Unlike function defined using def, lambda functions cannot have statements in its body (e.g. return, assert, raise). Remember from Week 1: x+y+z is an expression, not a statement!

The mathematicians among you might be familiar with lambda calculus, which is where lambda functions come from.

In Python, there is a time and place to use lambda functions, so you should not go crazy and start replacing all your functions with lambda functions.

“… the only advantage of using a lambda instead of a locally-defined function is that you don’t need to invent a name for the function … “ [source]

In general, if using lambda functions makes your code hard to read, then don’t use it!

In this module, we will look at ways when lambda functions can actually useful.