Lambda is another way of creating functions. There’s nothing intimidating about it, you’re already familiar with functions. The difference is lambda defines functions inline.

There’s nothing you can do with lambda that you can’t do with a normal Python function. Lambda functions work well on collections like lists.

Related course: Complete Python Programming Course & Exercises

Introduction

Lambda comes from the Lambda Calculus and refers to anonymous functions in programming. A function is anonymous if it doesn’t have a name. Python supports lambda functions.

A Python lambda function behaves like a normal function, when calling it. It’s in it’s definition that it’s different. If you have only the function call, you have no way of telling if it’s a regular or lambda function.

f(x)

Let’s start with a normal function and then create the lambda variant of it.
If we have a regular Python function def func(): like this one:

def f(x):
return x*x
You can create an anonymous function or lambda function that does exactly the same.

A lambda function is a small function that is often not more than a line, it can have any number of parameters and the body is just one expression.

Lamda function

To create a lambda function, write lambda followed by the parameters, then a colon and the expression.
So the syntax is:

lambda argument(s): expression

It can have multiple arguments, just like a regular function. But it’s body is an expression, a lambda operator cannot have any statements.

An anonymous function does not have a name, here we assign it to object f but that can be changed just as easily:

f = lambda x: x * x
y = f(4)
print(y)

You could create an anonymous function or lambda function that does exactly the same:

f = lambda x: x + 1
y = f(5)
print(y)

An example of the lambda function with two parameters:

f = lambda x, y: x * y
y = f(2,5)
print(y)

You combine it with map to apply the lambda function to each element:

values = [1,2,3,4,5,6,7]
square = lambda x: x * x
squared = list(map(square, values))
print(squared)

Related course: Complete Python Programming Course & Exercises

Why Use Lambda Functions?

Lambda functions are to be used only for functions that need exist for a short time frame. If you don’t need a function for what you are trying to do now, you can create one.

This makes your code much more readable, than having hundreds of tiny functions that do something like

def pow(num):
return num*num

You can have the more readable lambda alternative:

pow = lambda x: x*x
pow(3)

If you are a Python beginner, then I highly recommend this book.

Download exercises