Understand Lambda Function with a Simple Example in Python

What is a lambda function?

A lambda function is often called an anonymous function, which you will understand in a moment. The difference between a simple function and a lambda function is small.

Let’s try with an example to explain it.

def multiply_two(x):
    return 2*x

print(multiply_two(10))

my_lambda = lambda x: 2*x

print(my_lambda(10))

Which both will return 20. The first one, multiply_two, is a simple function that has a return statement. The lambda function does the same, just defined differently.

Looking at the lambda function.

my_lambda = lambda x: 2*x

You see the structure that you use the key-word lambda and what it takes of input x and what it returns 2*x. In this case we assigned the lambda function to a variable my_lambda. This is not necessary as the use-case below will show.

Why use lambda functions?

It can be convenient to use lambda functions in cases where you want to make simple operations.

Again, a simple example will demonstrate it.

def apply_to_list(the_list, f):
    return [f(x) for x in the_list]


the_list = [6, 3, 9, 1, 4, 2, 8]
print(apply_to_list(the_list, lambda x: x + 5))
print(apply_to_list(the_list, lambda x: x*2))

Which will return.

[11, 8, 14, 6, 9, 7, 13]
[12, 6, 18, 2, 8, 4, 16]

That is nice. You can easily define small functions to make simple functionality you might only need once.

When you understand the syntax of lambda functions it is easy.

Alternatively, you could use the following code the get the same result without using the lambda function.

print([x + 5 for x in the_list])
print([x*2 for x in the_list])

The simplicity of these examples are only meant to teach that lambda functions gives you some flexibility in your programs.

Leave a Reply