Map, Filter & Reduce Functions In Python. Topic 37

Map Filter Reduce Functions

Map:

The concept of map filter and reduce is one of the most important concepts in Python. Most of the time these three methods will be used for list manipulation. Using these three functions you can write more beautiful code.

First, we will see what is the map function. The map function is a built-in Python function. In Python, it applies a specific function to each element of an iterable, and a new iterable(list) is created which contains the modified values.

Let’s assume that, I want to calculate the cube of a number. If we do this normally by creating a function. Let’s see an example:

def cube(num):
    return num * num * num

print(cube(3))

The Output Will Be :

Output
27

Suppose I have a list and I have to cube the number of items in that list. and then store the value in a list. So let us see how to do it in an example.

def cube(num):
    return num * num * num

print(cube(3))

my_lists = [1,2,3,4,5,6]
new_list = []
for my_list in my_lists:
    new_list.append(cube(my_list))

print(new_list)

The Output Will Be :

Output
[1, 8, 27, 64, 125, 216]

How much pain, to write this program? At first, create a function, then create a blank list then append these values. Too much pain to do this. So much more for a lazy programmer like me. So there is no shortcut to this? yes, of course, there is a shortcut. To short this program there is a method that is called the map function.

my_lists = [1,2,3,4,5,6]

def cube(num):
    return num * num * num

new_list = map(cube, my_lists )
print(new_list)

The Output Will Be :

Output
<map object at 0x0000021EE2EEA170>

Will these things work? Yes, it will work but the program will return a map object. but you can convert this thing easily. Let’s see the example.

my_lists = [1,2,3,4,5,6]

def cube(num):
    return num * num * num

new_list = list(map(cube, my_lists ))
print(new_list)

The Output Will Be :

Output
[1, 8, 27, 64, 125, 216]

Let’s explore another example. Create a function to get the square value of a number.

# Function to square a number
def square(x):
    return x ** 2

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Using map to square each element in the list
squared_numbers = map(square, numbers)

# Converting the map object to a list
result_list = list(squared_numbers)

print(result_list)

The Output Will Be:

Output
[1, 4, 9, 16, 25]

In the previous chapter, we already read about the lambda function. We can use the map function through the lambda functions. It will be a more short program.

my_lists = [1,2,3,4,5,6]
new_list = list(map(lambda x: x*x*x, my_lists))
print(new_list)

The Output Will Be:

Output
[1, 8, 27, 64, 125, 216]

Here, the map function applies the square function to every element of the numbers list and makes a new list, In which every element has become square. The syntax of the map function looks like this:

map(function, iterable)
  • function: The function, that we want to apply to each element.
  • iterable: The sequence whose function is to be applied to each element.

Purpose of the map function:

The purpose of a map is to apply a function to each element of a sequence and is an efficient way to modify values.

Filter:

Now see, what is the filter function? If I ask you a simple question, what is the filter? So filter is that which filters something. That filter we use at our home for purifying the water. If we think, about the logic behind the water filter. We give some water and if the water is not clean, then it will filter the water. but if the water is already cleaned, then it does nothing, just throw the water.

Filter functions in Python work in a similar way. Assume we give a condition. filter function will filter according to the given condition.

Filter is also a built-in Python function. Which filters the elements of an iterable (such as a list) based on a specific condition. A new iterable is created which includes only those elements that satisfy or pass the condition. Let’s see an example:

def is_even(x):
    return x % 2 == 0

Next step, Now we will create a list of numbers. And we will give two things to the filter functions. first one is the is_even() function and the second one is the list that we want to filter. Filter functions filter all even numbers and store these even numbers in the new list. Always remember, that the filter function always returns a filter object. But we can simply typecast to the list. So let’s see how it works:

# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using filter to get only even numbers
even_numbers = filter(is_even, numbers)

# Converting the filter object to a list
result_list = list(even_numbers)

print(result_list)

The Complete Programme Look Like This:

def is_even(x):
    eturn x % 2 == 0


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(is_even, numbers)
result_list = list(even_numbers)

print(result_list)

The Output Will Be:

Output
[2, 4, 6, 8, 10]

Let’s see what happens in this program. Filter function applies the is_even function to each element in the list. But the filter function adds only these elements, that qualify or pass the condition, which means add only the even number. Qualified numbers are stored in the result_list variable. The Syntex of the filter function looks like this:

filter(function, iterable) 
  • function: The function you want to check for each element.
  • iterable: The sequence (such as a list) on which the function is to be applied to each element.
  • The function of `filter` is to filter the elements of any iterable on the basis of the specific condition.

In the previous chapter, we already read about the lambda function. We can use the map function through the lambda functions. It will be a more short program.

# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using filter with a lambda function to get only even numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)

# Converting the filter object to a list
result_list = list(even_numbers)

print(result_list)

The Output Will Be:

Output
[2, 4, 6, 8, 10]

Reduce:

Reduce is also a built-in Python function. `reduce` is a built-in function in Python that takes an iterable (such as a list) and combines all its elements with a specific function, ultimately generating a single value. The basic idea to use the reduce function is to iteratively apply a specified function to the elements of a sequence, gradually combining them to produce a final result. The most important thing is to reduce the function that must be imported to use it. Let’s understand through an example:

from functools import reduce

numbers = [1, 2, 3, 4, 5]
def add(x,y):
    return x + y

sum = reduce(add, numbers)
print(sum)

Here, the `reduce` function applies the `add` function to every two adjacent elements of the numbers list. At first, add 1 and 2. The result is 3, then add 3 with the previous value that was 3. Now 3+3 = 6. result of this 15, is the sum of all these numbers. We can create this same thing by using the lambda function. Let’s see the magic:

from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce (lambda x,y: x + y, numbers)
print(result)

# Using reduce with a lambda function to calculate the sum
sum_result = reduce(lambda x, y: x + y, numbers)

print(sum_result)

The Output Will Be:

Output
15
Lambda Functions I Python

Lambda Functions In Python

There is a concept of lambda functions in Python which is very useful. To write an anonymous function, there …

Practice Set For Map Function:

  • Given a list of integers, use the map function to create a new list where each element is squared.
  • Create a list of strings, each representing a number. Use the map function to convert the strings to integers.
  • Given two lists of integers, use the map function to find the sum of corresponding elements in the two lists.
  • Use the map function to square the even numbers and cube the odd numbers in a list of integers.
  • Given a list of names, use the map function to create a new list where each name is reversed. For example, “John” should become “nhoJ.”

Practice Set For Filter Function:

  • Given a list of integers, use the filter function to create a new list containing only the even numbers.
  • Create a list of strings representing names. Use the filter function to create a new list containing only names that start with the letter ‘A’.
  • Given a list of integers, use the filter function to create a new list containing only numbers greater than 10.
  • Given a list of words, use the filter function to create a new list containing only the words that have more than five letters. Use the map function to convert these words to uppercase.
  • Given a list of email addresses, use the filter function to create a new list containing only the addresses ending with “.com”.

Practice Set For Reduce Function:

  • Use the reduce function to find the product of all elements in a list of integers.
  • Given a list of strings, use the reduce function to concatenate them into a single string.
  • Given a list of integers, use the reduce function to find the sum of only the even numbers.
  • Given two lists of integers, use the reduce function to find the product of corresponding elements in the two lists.
  • Given a list of words, use the reduce function to find the longest word.

I hope you understand “Map, Filter & Reduce Functions In Python. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

4 Responses

  1. ”’
    given a list of integer ,use the map function to create a new list where each element
    is squard’
    ”’
    list1=[1,2,3,4,5,6,7]
    def squard(num):
    return num*num
    result=(list(map(squard,list1)))
    print(result)

  2. given a list of names ,use the map function to create a new list
    where each name is reversed.for example,”falguni”should become “inuglaf”
    ”’
    list1=[‘falguni ‘,’is a’,’good girl’]
    x=(list(map(reversed,list1)))
    print(x)

    It’s not working, got some error

    1. Check this programme. I fixed it. This Python code reverses each string in the list `list1` using the `reversed_string` function and stores the reversed strings in a new list `x`.

      list1=[‘falguni ‘,’is a’,’good girl’]
      def reversed_list(num):
      return num[::-1]
      x=(list(map(reversed_list,list1)))
      print(x)

Leave a Reply

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

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog