Lambdas

In Python, functions are values. You can store a function in a variable and call it using that variable's name. A lambda is a small function with no name of its own. It is written as a single expression.

greet = lambda name: "Hello, " + name
print(greet("Maya"))

Output:

Hello, Maya

lambda name: "Hello, " + name takes a name and gives back a greeting. The part before the colon, name, is the parameter. The part after the colon is the value the lambda gives back. The variable greet holds this function, so greet("Maya") calls it.

A lambda does not use the return keyword. It can hold only one expression.

This lesson stores lambdas in variables so you can see them work. In real code, you usually write a lambda right where another function needs a small function. One example is the key for sorting, which you will meet in the Comprehensions section. When you want a function with a name, def is clearer.

In the exercise, write a lambda that adds five to a number.