In this article, we will learn about lambda function in python with example and its use in map(), filter(), reduce() functions and list comprehension with sample programs and explanation.

Lambda function
A lambda function is a function without a name or commonly called anonymous function. This function is defined with the keyword lambda and consists of a short one liner expression.
This means that it can only be used where a function with a single statement is required.
A lambda function is defined using the below syntax

lambda <arguments>: expression

lambda is a keyword.
arguments are the function arguments. If there are multiple arguments, they must be separated by a comma(,).
expression is the function body consisting of a single statement.

Example of a lambda function is

lambda a,b: a * b

This is a lambda with two arguments which returns the product of its arguments.
A lambda function returns a function object. Thus, you may assign it to a variable as below.

# lambda function assigned to a variable
fun = lambda a,b: a * b

which prints

<function <lambda> at 0x109b01550>

This is a function object along with its memory address.

Invoking lambda function
In the last section, we saw how to create a lambda function.
A lambda function is invoked similar to a normal function by using the name of the variable followed by the parenthesis and supplying its arguments inside the parenthesis as shown below

fun(5, 10)

A lambda function can also be invoked directly where it is defined without assigning it to a variable as below

(lambda a, b: a * b)(5, 10)

This will return the result returned by the lambda function.
Lambda function example
Below is an example of a lamdba function which accepts a string argument and converts it to upper case.

# create a lambda function
to_caps = lambda str: str.upper()
# invoke lambda function
upper_case = to_caps('python')
print('String converted to upper case:', upper_case)

which prints

String converted to upper case: PYTHON

Lambda function lambda str: str.upper() defined in this example is equivalent to the below function

def to_upper(str):
   return str.upper()

Lambda function with list comprehension
Python list comprehension can also be performed using a lambda function. List comprehension is used to create a list from an existing sequence.
It has following syntax

list = [ expression for item in sequence ]

Example of list comprehension is given below.

caps = [letter.upper() for letter in 'python']

Above statement creates a list of letters in upper case from the word “python”.

In place of the expression, you can use a function and this function could be a lambda function. Thus, above example can be modified to use lambda function as

# create a lambda function
upper_case = lambda l: l.upper()

# list comprehension using lambda function
caps = [upper_case(letter) for letter in 'python']

Instead of assigning lambda function to a variable and then using it in expression, you can directly use it as below

caps = [(lambda l: l.upper())(letter) for letter in 'python']

If you are not familiar with List comprehension, read it in detail here.
Lambda with map()
Python map() function accepts a function and an iterable as arguments and returns another iterable. Its syntax is

result = map(function, iterable)

It invokes the function for each element of the iterable, supplies the element to the function and adds the value returned by the function to the result iterable.
Iterable may be a string, list or set. Example of map() function is

# Function to return the cube of its argument
def cube(num):
   return num ** 3

cubes = list(map(cube, [1,2,3,4]))

This example creates a new list with elements as the cube of the original list. map() returns an iterable which is converted to a list using its constructor.
Note that the function as the first argument to map() is defined at the top.

Above usage of map() can be modified to use lambda function as the first argument as shown below.

# define a lambda function
cube = lambda num: num ** 3

cubes = list(map(cube, [1,2,3,4]))

Instead of assigning lambda function to a varibale and then using it with map(), you can directly use it as below.

cubes = list(map(lambda num: num ** 3, [1,2,3,4]))

In this example, lambda function accepts single argument(num) and returns its cube value.

Lambda with filter()
Python filter() function is used to remove or filter out some items from an iterable based on a condition.

filter() accepts two arguments.
First one is a function which should return True or False, and
Second is the iterable.

Argument function is called for each element of the iterable passing the element to the function.
If the function returns True, this element is included in the result iterable otherwise it is ignored. Example,

# function to check if argument is greater than 18
def is_adult(age):
    return age >= 18

# source list
ages = [5, 10, 21, 45, 35, 65]
# get ages greater than 18
adults = filter(is_adult, ages)

which prints

[21, 45, 35, 65]

Look it removed elements that are lesser than 18.

Argument function supplied to filter can be replaced with a lambda function as shown below.

ages = [5, 10, 21, 45, 35, 65]
adults = filter(lambda age: age >= 18, ages)

which returns exactly the same result.
In this example, lambda function accepts one argument(age), compares it with 18 and returns the True or False.
You can see that the code is much cleaner and shorter.
Lambda with reduce()
Python reduce() function is used to reduce the elements of an iterable to a single result. Simplest example would be to add the elements of a list.
reduce() expects a function and an iterable as arguments. Example of reduce() function is given below.

from functools import reduce

def add_numbers(num1, num2):
    return num1 + num2

numbers = [5, 10, 21, 45, 35, 65]
sum = reduce(add_numbers,numbers)
print('Sum of numbers:', sum)

This prints
Sum of numbers: 181

Lambda function can be used with reduce() as the first argument as shown below.

from functools import  reduce

numbers = [5, 10, 21, 45, 35, 65]
sum = reduce(lambda x,y: x + y, numbers)
print('Sum of numbers:', sum)

In this example, lambda function accepts two arguments(x and y) and returns their sum.
That is all on Lambda function in python and its use with map(), filter(), reduce() functions and list comprehension. Hope the article was useful.

Liked the article ? Spread the word...

Leave a Reply