Lambda Functions in Python | Map, Filter, and Reduce

Raghav Agrawal 22 Mar, 2022 • 6 min read

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

Introduction

Hello, and welcome to the beautiful article where we will learn and discuss various facts related to python Lambda functions. Python is a dynamic yet straightforward typed language, and it provides multiple libraries and in-built functions. There are different methods to perform the same task and in Python lambda function proves to be king of all, which can be used everywhere in different ways.

1. Introduction to Lambda Function
2. Difference between Lambda function and Normal Function
3. Why should the Lambda function be used?
4. In-Built High order Lambda Functions in Python
5. Alternative ways to High-order Functions
6. End Notes

Brief Overview on Lambda Functions

Lambda function is also known as anonymous(without a name) function that directly accepts the number of arguments and a condition or operation to perform with that argument which is colon-separated and returns the final result. To perform a small task while coding on a large codebase or a small task inside a function, we use the lambda function in a normal process. Now let’s see how it is different from the normal position.

Difference between Normal Functions and Lambda Functions

1) No name – Lambda functions have no name, while normal operations have a proper name.

2) Lambda has no return Value – the normal function created using def keyword returns value or sequence data type, but a complete procedure is returned in the lambda function. Suppose we want to check the number is even or odd, so lambda function syntax is like the snippet below.

```b = lambda x: "Even" if x%2==0 else "Odd"
b(9)```

3) A function is only in one line – Lambda function is written and created only in one line while in a typical process we use indentations

4) Not used for Code reusability – Lambda function cannot be used for code reusability, or you cannot import this function in any other file. In contrast, standard functions are used for code reusability, which you can use in external files.

Why should we use Lambda Functions?

In typical scenarios, we do not use the Lambda function while we use it with higher-order functions. Now higher-order functions are the functions that need one more function in them to accomplish their task, or when one function is returning any another function, then we use Lambda functions.

What are Higher Order Functions?

Let’s understand higher-order functions with the help of an example. Suppose I have an integer list, and we have to return three outputs.

• a sum of all even numbers in a list, a sum of all odd numbers in a list, a sum of all numbers that are divisible by three

Now, suppose you approach this problem using normal function. In that case, you will declare three different variables that store various tasks and use one for loop and return the resultant three variables. This is a good approach and will work fine. Now, if we want to do it with the Lambda function, then how we can solve it is we can use three different lambda functions to check a number even, odd, or divisible by three and add a number in a result. The code snippet is shown below.

```def return_sum(func, lst):
result = 0
for i in lst:
#if val satisfies func
if func(i):
result = result + i
return result
lst = [11,14,21,56,78,45,29,28]
x = lambda a: a%2 == 0
y = lambda a: a%2 != 0
z = lambda a: a%3 == 0
print(return_sum(x, lst))
print(return_sum(y, lst))
print(return_sum(z, lst))```

Here we have created a higher-order function where we have passed a part and have also changed the process’s behaviour. Currently, this type of code is floating everywhere on the internet, where people create a higher-order function to control the behaviour of a part. Now we will study some in-built higher-order tasks in Python. Most people working with Python skip using this function or use it for only a limited time, but these functions are handy and can save more code of lines to write.

Map Function

The map function is a function that accepts two parameters. The first is a function, and the second is any sequence data type that is iterable. The Map part is to apply a certain kind of operation defined in each element of the iterator object. Suppose we want to change the array elements into a square array means we want a square of each component of a variety to map a square function with an array that will produce the required result.

```arr = [2,4,6,8]
arr = list(map(lambda x: x*x, arr))
print(arr)```

We can use the map function in different ways. Suppose we have a list of dictionaries containing details like name, address, etc. Now we have to generate a new list that includes all names.

```students = [
{"name": "John Doe",
"father name": "Robert Doe",
},
{
"name": "Rahul Garg",
"father name": "Kamal Garg",
},
{
"name": "Angela Steven",
"father name": "Jabob steven",
}
]
print(list(map(lambda student: student['name'], students)))```

Source: Author

This type of work you do when you fetch data through a database or web scraping.

Filter Function

Filter function filters out the data based on a particularly given condition. Map function operates on each element, while filter function only outputs elements that satisfy specific requirements. Suppose we have a list of fruits, and our task is to output only those names which have the character “g” in their name.

```fruits = ['mango', 'apple', 'orange', 'cherry', 'grapes']
print(list(filter(lambda fruit: 'g' in fruit, fruits)))```

Reduce Function

It is one exciting function that is not directly present in Python, and we have to import it from the functional tools module of Python. Reduce returns a single output value from a sequence data structure because it reduces the elements by applying a given function. Suppose we have a list of integers and find the sum of all the aspects. Then instead of using for loop, we can use reduce function.

```from functools import reduce
lst = [2,4,6,8,10]
print(reduce(lambda x, y: x+y, lst))  #Ans-30```

We can also find the most significant or more minor element from a list using reduce function instead of the loop.

```lst = [2,4,6,8]
#find largest element
print(reduce(lambda x, y: x if x>y else y, lst))
#find smallest element
print(reduce(lambda x, y: x if x<y else y, lst))```

List Comprehension

List comprehension is nothing but a for loop to append each item in a new list to create a new list from an existing index or a set of elements. The work we have performed using Map, filter, and reduce can also be done using List Comprehension. Hence, the motive to study this is most people prefer list comprehension instead of using Map and filter function because it is easy for some to apply and remember.

Suppose we want to change array elements to their square using list comprehension, and the fruit example can also be solved using list comprehension.

```arr = [2,4,6,8]
arr = [i**2 for i in arr]
print(arr)
fruit_result = [fruit for fruit in fruits if 'g' in fruit]
print(fruit_result)```

Dictionary Comprehension

Same as List comprehension, we use dictionary comprehension to create a new dictionary from the existing one. We can also create a dictionary from a list of elements. Suppose we have a list of integers and want to create a dictionary where each value is a key, and its square is its value. So to make this, we can use Dictionary comprehension.

```lst = [2,4,6,8]
D1 = {item:item**2 for item in lst}
print(D1)
#to create a dict of only odd elements
arr = [1,2,3,4,5,6,7,8]
D2 = {item: item**2 for item in arr if item %2 != 0}
print(D2)```

This is a small thing required at different levels of coding, but we are stuck in using loop under loops.

End Notes

We have learned what a lambda function is and a requirement of a lambda function. After that, we studied higher-order functions and some pre-built high-order functions in Python and how we can use the lambda function in high-order functions. Apart from this, we have also taken a small look over alternate methods to perform this in list comprehension and dictionary comprehension. These are the tiny and essential things that while reading might feel like you know this or you have seen this previously but I promise that till now you have used it very few times or never used so the basics are essential to take care of and should be used in a large codebase.

I hope that every term is clear to you. If you have any doubts, please post them in the comment section below, or you can connect with me.

Check out my other articles on Analytics Vidhya and Blogger.