If you know what a higher order function is then map(), filter(), and reduce()  are no different. These functions accept a certain function and processes the values according to passed function. They allow a programmer to write simpler and shorter code without the need for traditional loops and multiple indentations. If you haven’t looked at higher-order functions, I suggest you learn about them here -> <link to tutorial>.

These functions accept an iterable and a function and apply the function to each element of the iterable. Map and filter are built-in functions in Python in the __builtins__ module, but reduce has to be imported from the functools module.

map()

 map() is a built-in function in Python that applies a given function to each element of an iterable (e.g., a list, tuple, set) and returns a new iterable object containing the transformed values.

The map() function takes two arguments: the first argument is the function to be applied, and the second argument is the iterable to be mapped.

Let’s look at a traditional way of squaring each number from a list of elements and making a new list out of the results.

nums = [1, 2, 3, 4, 5]
squares = []
# Function to square a given number
def squaring(num):
    return num * num

for i in nums:
    square = squaring(i)
    squares.append(square)

print(squares)
# -> squares = [1,4,9,16,25]

This was a traditional method of performing the operation. Now let’s use the map() function.

nums = [1,2,3,4,5]
def squaring(num):
     return num * num
     
squares = map(squaring,nums)

print(squares)
# -> <map object at 0x000001512FA6AAA0>
print((list(squares)))
# -> [1,4,9,16,25]

Point to be noted:

In Python 3, map() returns an iterator object that generates the results lazily, meaning that it doesn’t actually apply the function to the elements of the iterable until you start iterating over the results.

To see the results of the map() operation as a list, you need to convert the iterator object to a list using the list() method

To make all of this even shorter you can use a lambda function. This is one of the most useful case of using a lambda function

nums = [1,2,3,4,5]
squares = map(lambda num : num*num,nums)
print((list(squares)))
# -> [1,4,9,16,25]

filter()

In Python, filter() is a built-in function that allows you to extract a subset of items from an iterable object (such as a list, tuple, or set), based on a Boolean-valued function that you provide.

To use the filter() function, you need to provide it with two arguments: the first argument is a function that will evaluate each item in the iterable, and the second argument is the iterable object itself. filter() will then generate a new iterator that only includes the items for which the evaluation function returned True

For example,

# List of only the numbers that are exactly divisible by three 

nums = [1,3,7,9,12,21,19,29]

# using a lambda function in filter
# Lambda function checks if a given number x is divisible by 3 or not
# if the number is not divisible by 3 then it is not included in the result.

result = filter(lambda x :x % 3 == 0,nums)
print(result)
# -> <filter object at 0x00000203525AAAA0>
print(list(result))
# -> [3,9,12,21]

Similar to map, we need to convert the map iterable object into a list that contains the mapped values

 

Reduce()

We used Map() and Filter() to get a list of modified values and a list of filtered values right? So reduce does not actually returns a list, instead it returns the a single aggregate value based on the function we provide to this method.

The syntax to reduce is as follows

val = reduce(function,iterable,initializer=None)

The new thing in reduce is that it accepts another argument called initializer. We will look at an example with and without an initializer in the examples below.

In this example, we will be multiplying all the numbers one by one from the given list and the end product will be a single value.   

from functools import reduce

numbers = [5,10,1,2,4,12]
product = reduce(lambda x, y: x * y, numbers)
print(product)
# -> 4800

In the above example, we don’t have any initializer, which means the actual initial value is the first number in the list

If we set the initializer to a certain number then, the multiplication will begin from the initial value.

For example, let’s do a sum of all the numbers from a list

from functools import reduce

numbers = [5,10,1,2,4,12]
sum_of_list = reduce(lambda x, y: x + y, numbers,10)
print(sum_of_list)
# -> 44

If there was no initializer, then our value would have been 34 but since we have 10 as an initializer, we get 44 as a result.

In summary:

  • map(): Creates a new list by applying a function to each element in an iterable.
  • filter(): Returns a new list of elements from an iterable that satisfy a given condition defined by a function.
  • reduce(): Applies a function to an iterable and reduces it to a single value. It takes three arguments: a function, an iterable, and an optional initializer value. It needs to be imported from the functools module.

Leave a Reply

Your email address will not be published. Required fields are marked *