What is Lambda Functions ?

Posted by Anuprabha on 18-Feb-2022

While working with Python you would have often come across the term lambda functions or lambda expressions. They are quite popular and useful at times.

Python lambda functions are anonymous functions, that is, a function has no name.

The syntax is pretty simple

lambda argument(s): expression

lambda is the keyword used to define an anonymous function in Python, just like def is used to define a normal function.

Here is an example that shows the difference between a lambda function and a normal function,

function to find the square of a number

def square(n):
    return n*n

print(square(5))

Output

25

Square function using lambda

lambda n: n*n

This is the equivalent lambda expression that takes the argument n and returns n*n. But we cannot use it because it does not have a name. We need to assign it to a name so that we can use it like any other function by passing an argument.

num_square = lambda n: n*n

print(num_square(5))

Output

25

Lambda functions can have any number of arguments, but only one expression. It is even possible to have a lambda function with no arguments at all.

We will look at some more examples for clarity,

Combine the first name and last name of a user

full_name = lambda fn, ln: fn + “ “ + ln

print(full_name(“Guido”, “Rossum”))

Output:

Guido Rossum

Add three numbers

result = lambda x, y, z: x+y+z
print(result(2, 3, 4))

Output:

9

lambda functions are useful when we want a simple function that will be used only once in the program. This will make the code more compact and readable.

However, assigning names to lambda functions is less common as they are anonymous functions and are not supposed to be stored in memory. If we want to create a function that we will store and reuse, we define a normal function using the def keyword.

A lambda function is most useful when it is used inside another function. They are generally used with higher-order functions like map() and filter().