An Explanation to Python’s Lambda, Map, Filter and Reduce

Harsh Last Updated : 21 Oct, 2024
5 min read

This article was published as a part of the Data Science Blogathon

Introduction

Hola folks. Have you ever got confused in Python’s Lambda, Map, Filter, and Reduce? Huh? No worries, I’ve got you covered. In this article, we will be clearing all the confusion you might have had. Specifically, after reading this article, you will know:

  • What is Lambda, Map, Filter, and Reduce?
  • Why do we use Lambda, Map, Filter, and Reduce?
  • How to use Lambda, Map, Filter, and Reduce?
  • When to use Lambda, Map, Filter, and Reduce?

If you don’t have any confusion on this topic, you can directly move on to the Summary section.

 

Table of Contents

  1. Lambda
  2. Map
  3. Filter
  4. Reduce
  5. Summary
  6. Endnotes

 

Lambda

Lambda is a keyword in Python used to define functions, more specifically Anonymous Functions, and such functions are known as Lambda Functions or Lambda Expressions.

Here’s a syntax to define a Lambda Function.

lambda arguments: expression

Let us understand this with an example.

What If I ask you to write a function to square a number? You would probably write something like the following:

def square(n):
    return n ** 2

The code shown above is self-explanatory and isn’t Pythonic. There we have lambda functions to make it Pythonic. Following is the square equivalent function using lambda:

square = lambda n: n ** 2

The expression n ** 2 gets evaluated first, and a value gets returned to the identifier square. The identifier square can now act as a function, and thus we can pass any number as an argument to find the square of a number.

# Calling lambda function
square(5)
# Output: 25

We can also extend the lambda functions by adding conditional statements. Refer to the following self-explanatory example.

maxi = lambda x, y: x if x > y else y
maxi(4, 6)
# Output: 6

So, that’s about making your code Pythonic using lambda. But that’s not all that lambda does. It is also often used to create function wrappers, such as Python’s decorators. Following is one such example.

def transform(n):
    return lambda x: x + n
f = transform(3)
print(f(4))

# Output: 7 (3 + 4)

 

The transform function takes in a number and returns the lambda expression/function. Lambda function further adds two numbers, x and n.

The limitation of Lambda functions is that they can have any number of arguments but only one expression.

Lambda functions are mainly used with the map functions as in-place functions. So, let’s discuss the map functions.

Map

What If I ask you to find a square of the first five odd numbers. You would probably write something like the following:

squares = []
for n in range(1, 10, 2):
    squares.append(n ** 2)

The loop iterates through 1 to 10 with a step size of 2 and appends the square of each number to squares. The approach shown above can be improved using list comprehension but that too will use for loop. So, there’s a faster way to do the same without using explicit for loop. Python’s map function does that. It transforms the given iterable based on the given condition.

The syntax for the map function is as follows:

map(function, iterable)

The map function takes in a function and an iterable(list, tuple, etc.) as an input; applies passed function to each item of an iterable and returns a map object(an iterator).

Let us re-implement the above example using the map function.

def square(n):
    return n ** 2
squares = map(square, range(1, 10, 2))  
squares
# returns map object
list(squares)
# Output: [1, 9, 25, 49, 81]

The square function returns the square of any number. The map function takes in square function and range(1, 10, 2) as arguments. It applies the square function on a given range(1, 3, 5, 7, and 9) which returns a map object and is later converted into the list.

The code above is longer than the earlier one. Thus, let’s make it pythonic using a lambda function. Have a look at the following self-explanatory code.

squares = list(map(lambda n: n ** 2, range(1, 10, 2)))

Here, the lambda function is applied on a given iterable which returns a map object and is later converted into the list.

The map function can have multiple iterables. Let’s take a quick example to demonstrate the same.

num1 = [2, 4, 9]
num2 = [3, 8, 5]
result = list(map(lambda x, y: x + y, num1, num2))
result
# Output: [5, 12, 14]

Here, we have performed element-wise addition of lists.

Keep in mind that the map can take any iterable as an argument and not only a list.

Filter

Let’s say you want to find the odd numbers from a given list. A quick way to approach this problem is to use a for loop inside a list comprehension.

nums = [1, 34, 23, 56, 89, 44, 92]
odd_nums = [num for num in nums if num % 2 != 0]

The loop iterates through nums and stores every odd number. The conditional statement here filters out the even numbers and returns only the odd numbers. This kind of functionality is known as filtering.

Python’s filter does the same in a faster way. It has the same syntax as the map.

filter(function, iterable)

It works similarly to the map. It returns a filter object, unlike a map object.

Let us re-implement the above example using the filter function.

def find_odd(x):
    if x % 2 != 0:
        return x
nums = [1, 34, 23, 56, 89, 44, 92]
odds = list(filter(find_odd, nums))
print(odds)
# Output: [1, 23, 89]

Let us convert this find_odd function to a lambda function and rewrite the code to make it shorter.

nums = [1, 34, 23, 56, 89, 44, 92]
odds = list(filter(lambda x: x % 2 != 0, nums))
print(odds)
# Output: [1, 23, 89]

All the items of an iterable for which the lambda function evaluates to true will get added to the odd.

Reduce

Let’s say you want to compute a sum of the first five integers. You can write something like the following:

nums = [1, 2, 3, 4, 5]
summ = 0
for num in nums:
    summ += num
summ
# Output: 15

The loop iterates through nums and keeps adding all the numbers to summ. Again to make it pythonic, we have a function, i.e. Reduce.

The syntax for the reduce is as follows:

reduce(function, iterable, [, initializer])

The reduce applies a function cumulatively on all the items of an iterable and returns a single value. Don’t worry if you haven’t get it yet.

Let us re-implement the above example with the reduce function.

from functools import reduce 
nums = [1, 2, 3, 4, 5]
summ = reduce(lambda x, y: x + y, nums)
summ
# Output: 15

Refer to the following figure to understand what’s happening behind the scenes.

Python reduce | Lambda Map Filter Reduce

Image source: Author

 

Here, the sum is performed in cumulative/successive manner: ((((1 + 2) + 3) + 4) + 5).

Summary

Lambda

  • Function with many arguments but only one expression.
  • It helps to make our code pythonic and to create function wrappers.

Map

  • A function that applies a given function to each item of an iterable and returns an iterator.
  • It provides a faster way to transform an iterable based on the given condition.
  • It can have multiple iterables.

Filter

  • It has the same syntax as the map function.
  • It helps in extracting items from an iterable based on the given condition.

Reduce

  • It applies a function cumulatively/successively on each item of an iterable and returns a single value.

Endnotes

This completes today’s discussion. Thank you for reading this article! I hope you enjoyed this article and had fun reading it as much as I had while writing it 🙂

Did I miss something important or want to share your thoughts? Comment down below, and I’ll get back to you.

About the Author

I am Harsh Dhamecha, a final year undergrad student of Artificial Intelligence, Machine Learning Mentor, and aspiring Data Scientist. I write about Python, Machine Learning, and Deep Learning.

If you have any queries, you can directly email me, too boring huh? There we have LinkedIn and Twitter. I regularly write threads on Python, Machine Learning, Deep Learning, and Data Science on Twitter. Follow me to stay updated!

You can have a look at the other articles I have written.

Still, reading this article? Special thanks to you 🙌

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

Responses From Readers

Clear

Gursevak
Gursevak

Thank you for the article. You explained it very well. Is there a typo in the definition of reduce function? It is like : reduce(function, iterable, [, initializer]) Shouldn't it be : reduce(function, iterable, [ initializer])??

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details