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 python

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.

Lambda function syntax

A lambda function is defined using the below syntax

lambda <arguments>: expression

where,
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.

Lambda function python – Example

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
print(fun)

which prints

<function <lambda> at 0x109b01550>

This is a function object along with its memory address.

How to call lambda function

In the last section, we saw how to create a lambda function in python.
A lambda function is called or invoked in the same way as 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 with arguments

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 python 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']
print(caps)

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']
print(caps)

If you are not familiar with List comprehension, read it in detail here.

Lambda function python 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 function python 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)
print(list(adults))

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 python as shown below.

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

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 function python 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.

Lambda function python – MCQ

Below is a list of multiple choice questions(MCQs) around lambda function in python.
These can be used to test your understanding of the concept. Try to crack them without looking at the answers.

1. What is the primary purpose of a lambda function in Python?

a) To define a class
b) To create anonymous functions
c) To execute SQL queries
d) To handle exceptions

2. In Python, which keyword is used to define a lambda function?

a) define
b) lambda
c) func
d) def

3. Which of the following is a valid lambda function in Python?

a) lambda a, b: a + b
b) def add(a, b): return a + b
c) func(a, b): a + b
d) lambda a + b

4. What is the result of the following lambda function?

(lambda x: x * 2)(5)

a) 10
b) 25
c) 5
d) 55

5. Can a lambda function be used to define a recursive function?

a) Yes, as long as it doesn’t exceed a certain depth
b) No, lambda functions cannot be recursive
c) Yes, without any restrictions
d) Yes, but only for mathematical operations

6. What does map() do when combined with a lambda function?

a) Filters elements in a list
b) Applies the lambda function to each element in a sequence
c) Concatenates multiple lists
d) Creates a new dictionary

7. Which of the following statements is true regarding lambda functions?

a) They can have multiple expressions
b) They cannot take arguments
c) They can have a docstring
d) They can only be used in if statements

8. What is the main advantage of using a lambda function?

a) They are more memory-efficient
b) They are easier to debug
c) They allow for concise one-liners
d) They provide better performance

9. In a lambda function, how can you specify default values for arguments?

a) By using the default keyword
b) Lambdas cannot have default values
c) By using the default attribute
d) By specifying the default values after the colon

10. In Python, which built-in functions accept lambda functions as arguments?

a) print
b) len
c) filter and map
d) sum

11. Which of the following is a valid use case for a lambda function?

a) Complex data processing and analysis
b) Defining classes and objects
c) Simple, one-time-use operations
d) Handling file I/O operations

Answers

  1. b) To create anonymous functions
  2. b) lambda
  3. a) lambda a, b: a + b
  4. a) 10
  5. b) No, lambda functions cannot be recursive
  6. b) Applies the lambda function to each element in a sequence
  7. a) They can have multiple expressions
  8. c) They allow for concise one-liners
  9. b) Lambdas cannot have default values
  10. c) filter and map
  11. c) Simple, one-time-use operations


That is all on Lambda function in python, how to define and use it along with examples and its use with map(), filter(), reduce() functions and list comprehension.

Hope the article was useful.

Leave a Reply