map-filter-reduce

Introduction

map() and filter() are built-in function in Python library. These functions are generally written in one line and allow programmers to optimize the code length. Both map() and filter() function returns the map and filter object respectively. Both the function operates on iterables with a specified function. Generally, the lambda function is used instead of the normal Python function. While reduce() function resides on Python ‘functools’ module. Like others, it operates on iterables with specified functions. This function does not return the object but returns a single value after operating over iterables and the lambda function is used as a specified function.

 

Lambda function

Python provides an anonymous function named as lambda function where lambda is keyword not name. Lambda function is used where the function needs to be called only once. They are used to reduce the code size because the body of this function is written in a single line. Sometime lambda functions are returned from large functions.

How to write lambda function?

Syntax- lambda argument : expression

 

Let’s take a simple example that demonstrates the way to define a lambda function.

z  = lambda x: x * 2

This function returns the double of the input argument x and assigns it to z.

Let’s have a look at the operation of the lambda function and normal function.

import time

start = time.time()
x = lambda a : a ** 2
print(x(10))
end = time.time()
lambda_time = end - start
print("time consumed: ", lambda_time)

Output:

100
time consumed:  0.0009961128234863281

 

To have a clear understanding let’s take a look at a normal function carrying out the same task.

import time

start = time.time()

def squared(n):
    return n ** 2

print(squared(10))
end = time.time()
func_time = end - start
print("time consumed: ", func_time)
print("lambda function is ", func_time / lambda_time, "times faster.")

Output:

100
time consumed:  0.0010006427764892578
lambda function is  1.004547630445189 times faster.

We got the same output from both functions. We can see that the lambda function is much shorter, faster, and easy to write.

 

More examples on lambda function

def fun(a):
    return lambda b : (a + b) ** 2
r = fun(4)
print(r(4))

Output:

64

The main function takes a single argument and returns the lambda function. Since, python function are object so we can assign them to variable(r = fun(4)). Since ‘r’ is assigned with lambda function with a value of  4, we can call lambda function passing single argument b,  which returns the square of the sum.

 

Lambda function to reverse the string

x = lambda x : x[::-1]
print(x("NEPAL"))

Output:

LAPEN

The above lambda function returns the reversed form of string.

 

Lambda function to check the number greater than 5

y = lambda x : x>5
print(y(4))
print(y(7))

Output:

False
True

Here, lambda function returns True for x=7 and False for x = 4

 

Lambda function to check the given string is in uppercase or not

y= lambda x : x.isupper()
print(y("NEPAL"))
print(y("Ram"))
print(y("abc"))

Output:

True
False
False

 

map() function

map() function executes a specified function on iterables and returns map object. map() function is built-in function in python library.

Syntax- map(function, iterables)

Example

def cube(n):
    return n**3

x = map(cube , (1,2,3,4,5))
print(x)

Output:

<map object at 0x0000017AC0CB7048>

Well, the output is weird right? Why we are getting such output? The answer is simple. As we know that the map() function returns the map object, it is returning the address of it.

To get the actual output, we can convert values of x in the list and tuple.

print(list(x))

Output:

[1, 8, 27, 64, 125]

 

map() with lambda function

Let’s continue the same example

x = map(lambda x : x ** 3 , (1,2,3,4,5))
print(list(x))

Output:

[1, 8, 27, 64, 125]

 

filter() function

filter() function is built-in function of python library. This function filters the iterator with the help of a function based on the true and false values of iterables. If the value of a certain iterable returned by the function is true then assign the value and if the value of iterable returned by the function is false then it discards the iterable.

Syntax- filter(function, iterables)

Example of filter() function

def fun(n):
    if n % 2 != 0:
        return n
    
x = filter(fun , [1,2,3,4,5,6,7,8,9,10])
print(x)

Output:

<filter object at 0x00000205655AC388>

Since the filter() function also returns the filter object we got the same output as the map() function.

To print the values in x

for value in x:
    print(value, end = " ")

Output:

1 3 5 7 9 

 

filter() with lambda function

x = filter(lambda a : a % 2 != 0 , [1,2,3,4,5,6,7,8,9,10])
for ele in x:
    print(ele)

Output:

1
3
5
7
9

filter() function with lambda function looks clean and short.

 

reduce() function

reduce() function is not built-in function in python library. reduce() function resides in module called functools. reduce() function returns the single value using a specified function and itreables

Syntax- reduce(function, iterables)

Example on reduce()

from functools import reduce

itr = [1,2,3,4,5,6,7,8,9,10]
z = reduce(lambda x, y: x + y, itr)
print(z)

Output:

55

 

Conclusion

filter(), map() and reduce() function reduces the code length and easy to write. All three functions operate on iterables with a specified function.

We can use the normal function to carry out the task but using the lambda function the code looks very clean and short. map() and filter() always returns the object but reduce() function returns the single value operating over iterables.

Happy Learning 🙂

Check out this video to learn more about Map, Filter, and Reduce Functions

References:

Leave a Reply

Your email address will not be published.