What is a Lambda Function?
A lambda function is an anonymous function. They are also known as lambda operators or simply lambda.
While traditional functions are defined with the def keyword, lambda functions do not need a name (which is why they are called anonymous!).
Syntax of a Lambda Function
Python lambda functions are defined using the lambda keyword.
A lambda function has the following syntax:
lambda arguments: expressionwhere:
lambdais the keyword to start defining a lambda function- The colon is used to separate
argumentsandexpression
For example,
sum = lambda a,b: a+b
print(sum(5, 10)) # 15where:
a, bare argumentsa+bis the expression
Important Characteristics of Lambda Functions
A Python lambda function has the following characteristics:
No Statements Allowed
A lambda function can't contain any statements in its body.
Any statement, such as return, raise, pass or assert, will raise an error (SyntaxError).
double = lambda a: assert a*2Single Expression Only
A lambda function contains only a single expression.
Immediately Invoked Function Expression (IIFE)
A lambda function can be invoked immediately by calling it and passing the arguments in parentheses.
print((lambda x: x*2)(3)) # 6Arguments
Multiple Arguments
The lambda function can have more than zero, one or more arguments: simply separate them with a comma ,.
For example, define a lambda function that sum three values
sum = lambda a, b, c: a+b+c
print(sum(1, 2, 3)) # 6Pass Arguments to a Lambda Function
Like a normal function, a lambda function supports different ways of passing arguments:
- Positional arguments
- Keyword arguments
- Default argument
- Variable list of arguments (
*args) - Variable list of keyword arguments (
**args)
Below are summarized some examples:
add = lambda x, y, z: x+y+z
print(add(1, 2, 3)) # 6
add = lambda x, y, z: x+y+z
print(add(1, z=2, y=3)) # 6
add = lambda x, y=2, z=3: x+y+z
print(add(1)) # 6
add = lambda *args: sum(args)
print(add(1, 2, 3)) # 6
add = lambda **kwargs: sum(kwargs.values())
print(add(x=1, y=2, z=3)) # 6Lambda Closures
As in normal functions, lambda functions can also be a closure.
A closure in a normal function is as follows:
def multiply(x):
def inner_func(y):
return x+y
return inner_func
double_mult = multiply(2)
print(double_mult(10)) # 20
triple_mult = multiply(3)
print(triple_mult(10)) # 30Similarly, a lambda can be a closure.
multiply = (lambda x: (lambda y: x+y))
double_mult = multiply(2)
print(double_mult(10)) # 20
triple_mult = multiply(3)
print(triple_mult(10)) # 30Examples
Let's look at examples of common functions (map(), filter() and reduce()) and common usage with lambdas
Lambda Functions with map()
The map() function expects two arguments: a function and a list. map() takes the function, applies it to each element in the list, and returns the modified list.
Consider the following example where each item in the list is incremented by 1:
my_list = [1, 2, 3, 4, 5]
def increment(x):
return x+1
new_list = map(increment, my_list)
print(list(new_list)) # [2, 3, 4, 5, 6]
increment_lambda = lambda x: x+1
new_list_lambda = map(increment_lambda, my_list)
print(list(new_list_lambda)) # [2, 3, 4, 5, 6]Lambda Functions with filter()
The filter() function takes a function and applies it to each element in the list to create a new list with only those elements that cause the function to return True.
Consider the following example where the list is filtered and only even numbers are present in the new list:
my_list = [1, 2, 3, 4, 5]
def is_even(x):
return x%2==0
new_list = filter(is_even, my_list)
print(list(new_list)) # [2, 4]
is_even_lambda = lambda x: x%2==0
new_list_lambda = filter(is_even_lambda, my_list)
print(list(new_list_lambda)) # [2, 4]Lambda Functions with reduce()
The reduce() function applies a two-argument function cumulatively to the list elements, from left to right, to reduce the list to a single value.
Consider the following example where the sum of all elements is calculated:
from functools import reduce
my_list = [1, 2, 3, 4, 5]
def sum(x, y):
return x + y
result = reduce(sum, my_list)
print(result) # 15
sum_lambda = lambda x, y: x+y
result_lambda = reduce(sum_lambda, my_list)
print(result_lambda) # 15Lambda Function with if-else
Since if else is a statement, you can't use it in the expression of lambda functions.
You can use the if else conditional expression instead.
find_max = lambda x, y: x if x > y else y
print(find_max(1, 2)) # 2
print(find_max('a', 'z')) # zList Comprehension in a Lambda
List comprehension is an expression, not a statement, so you can safely use it in a lambda function.
For example, flatten a nested list with the lambda function:
list_flattener = lambda l: [item for sublist in l for item in sublist]
my_list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
print(list_flattener(my_list)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
my_list = [['a', 'b', 'c'], ['d', 'e']]
print(list_flattener(my_list)) # ['a', 'b', 'c', 'd', 'e']