Skip to main content

Python Lambda and Anonymous Functions

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!).

note

Lambda functions are often used to create one-line functions.

Syntax of a Lambda Function

Python lambda functions are defined using the lambda keyword.

A lambda function has the following syntax:

lambda arguments: expression

where:

  • lambda is the keyword to start defining a lambda function
  • The colon is used to separate arguments and expression
note

You do not need to use the return keyword because lambda does it automatically for you.

Furthermore, lambda functions can return multiple values, packing them in a tuple.

For example,

sum = lambda a,b: a+b

print(sum(5, 10)) # 15

where:

  • a, b are arguments
  • a+b is 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*2
# SyntaxError: invalid syntax

Single Expression Only

A lambda function contains only a single expression.

note

The expression can be on multiple lines using parentheses or a multiline string, but it still remains a single expression!

double = (lambda a: 
a*2)
print(double(3)) # 6

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)) # 6

Arguments

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

# A lambda function that sum three values
sum = lambda a, b, c: a+b+c
print(sum(1, 2, 3)) # 6

Pass 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:

# Positional arguments
add = lambda x, y, z: x+y+z
print(add(1, 2, 3)) # 6

# Keyword arguments
add = lambda x, y, z: x+y+z
print(add(1, z=2, y=3)) # 6

# Default arguments
add = lambda x, y=2, z=3: x+y+z
print(add(1)) # 6

# *args
add = lambda *args: sum(args)
print(add(1, 2, 3)) # 6

# **args
add = lambda **kwargs: sum(kwargs.values())
print(add(x=1, y=2, z=3)) # 6
note

See arguments of traditional functions for more details (since the arguments are the same for both functions and lambdas).

Lambda 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)) # 30

Similarly, 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)) # 30

Examples

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]

# with traditional function
def increment(x):
return x+1

new_list = map(increment, my_list)
print(list(new_list)) # [2, 3, 4, 5, 6]

# with lambda function
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]

# with traditional function
def is_even(x):
return x%2==0

new_list = filter(is_even, my_list)
print(list(new_list)) # [2, 4]

# with lambda function
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]

# with traditional function
def sum(x, y):
return x + y

result = reduce(sum, my_list)
print(result) # 15

# with lambda function
sum_lambda = lambda x, y: x+y

result_lambda = reduce(sum_lambda, my_list)
print(result_lambda) # 15

Lambda 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.

# A lambda function that returns the bigger item
find_max = lambda x, y: x if x > y else y

print(find_max(1, 2)) # 2
print(find_max('a', 'z')) # z

List 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']
note

See Python lists and List Comprehension to learn more!