Python Lambda - Anonymous Function


Python supports nameless functions called lambda functions. This is sometimes called an anonymous function. You can create anonymous function using the lambda keyword.

A lambda function can have only one expression, but can have multiple arguments. The expression is evaluated and it returns the result.

Lambda functions are frequently used with the map(), filter(), and reduce() operations.

Related course: Complete Python Programming Course & Exercises

Python lambda Function Syntax

The lambda function syntax is:

lambda arguments : expression

Python Anonymous Function Example

A traditional function has a name, so you could have something like this:

def sum(a,b):
    return a+b

def ml(a,b):
    return a*b

print(sum(3,4))
print(ml(3,4))

You can create anonymous functions like this:

x = lambda a, b: a + b
print(x(3,4))

x = lambda a, b: a * b
print(x(3,4))

python lambda anonymous function

When to use Anonymous Function?

You should use lambda functions for small tasks that have low complexity. Function can have one and only one single expression.

Lambda Function with map()

The map() function takes a function and an iterable as the arguments, then it applies the function to every element in the iterable.

Lets say you want to take every number squared:

ln = [1, 2, 3, 4, 5, 6]
ln = map(lambda x: x*x, ln)

for num in ln:
    print(num, end=" ")

python lambda function map

Lambda Function with filter()

The filter() function takes a function and an iterable as the argument, then the function is applied to each element of the iterable.

But here's the difference: only if the function returns True, the element is added to the returned iterable.

ln = [1, 2, 3, 4, 5, 6]
ln = filter(lambda x: x % 2 == 0, ln)

for num in ln:
    print(num, end=" ")

python lambda filter

Lambda Function with reduce()

The reduce() function is part of the functools module. This reduce function takes a function and a sequence as the argument.

The function should accept two arguments. The elements from the sequence are passed to the function along with the cumulative value. The final result is a single value.

from functools import reduce

ln = [1, 2, 3, 4, 5, 6]
total = reduce(lambda x, y: x + y, ln)
print(f'Sum of ln elements is {total}')

python lambda reduce