An Introduction to Python’s Map(), Filter(), and Reduce() Functions


Python is a versatile language that has many uses cases. One of its most powerful features is the ability to manipulate data using built-in functions like map(), filter(), and reduce().

In this blog post, we’ll take a brief look at each of these functions and how they can be used.

Python’s map() Function

The map() function is used to apply a function to every element in an iterable (e.g., a list).

For example, let’s say you have a list of integers and you want to square each element in the list.

You could do this using a for loop:

numbers = [1, 2, 3, 4, 5] squared_numbers = [] for i in numbers: squared_numbers.append(i**2) print(squared_numbers) # Output: [1, 4, 9, 16, 25]
Code language: Python (python)

However, using the map() function is much more concise and efficient:

numbers = [1, 2, 3, 4, 5] def square(i): return i ** 2 squared_numbers = map(square, numbers) print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
Code language: Python (python)

What is a lambda function?

A lambda function is a small function that doesn’t have a name.

Any number of arguments can be passed to a lambda function, but it can only have one expression.

lambda arguments : expression
Code language: JavaScript (javascript)

Example

x = lambda x : x + 5 print(x(5)) # output: 10 x = lambda x, y : x * y print(x(5, 5)) # output: 25
Code language: Python (python)

And using the map() function with lambda.

numbers = [1, 2, 3, 4, 5] squared_numbers = map(lambda i: i**2, numbers) print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
Code language: Python (python)

As you can see from the above example, using map() is much simpler than using a for loop—and it’s also more efficient because map() is written in C (the programming language that Python is written in).

map() can be used with multiple iterables as well.

For example:

$python >>> numbers = ['1', '2', '3'] >>> letters = ['a', 'b', 'c'] >>> print(list(map(lambda x: x[0]+x[1], zip(letters, numbers)))) ['a1', 'b2', 'c3']
Code language: Python (python)

As you can see from the above example code snippet, we were able to use map() to add corresponding elements from our two lists together. Pretty neat!

Python script 1 – map() Function

# Without using lambdas def starts_with_A(s): return s[0] == "A" fruits = ["Apple", "Banana", "Pear", "Orange", "Apricot", "Strawberry"] map_obj = map(starts_with_A, fruits) print(list(map_obj)) #Output: [True, False, False, False, True, False]
Code language: Python (python)
# A prettier way to do this exact same thing is by using lambdas: fruit = ["Apple", "Banana", "Pear", "Orange", "Apricot", "Strawberry"] map_obj = map(lambda s: s[0] == "A", fruit) print(list(map_obj)) # We get the same output: [True, False, False, False, True, False]
Code language: Python (python)

Python script 2 – map() Function

Say I have a list (iterable) of my favorite fruit names, all in lower case and I need them in uppercase.

# Python 3 my_fruits = ['Apple', 'Banana', 'Strawberry'] uppered_fruits = list(map(str.upper, my_fruits)) print(uppered_fruits) #output: ['APPLE', 'BANANA', 'STRAWBERRY']
Code language: Python (python)

Python’s filter() Function

The filter () function returns an iterator that contains only the elements for which the specified function returns true.

So if you want to filter out all of the elements in a list that are not divisible by 2, you could do something like this:

nums = [1 , 2 , 3 , 4 , 5 , 6 ] even_nums = filter(lambda x : x % 2 == 0, nums) print(list(even_nums)) #Output [2 , 4 , 6 ]
Code language: Python (python)

Note how we were able to use a lambda expression inside of our filter () call. As with map (), it’s often more convenient (and efficient!) to use anonymous functions like lambda expressions rather than defining a full function.

If we had wanted to do the same thing without using Lambda expressions or list comprehensions we could have defined a function like this :

nums = [1 , 2 , 3 , 4 , 5 , 6 ] def even(num): return num % 2 == 0 even_nums = filter(even, nums) print(list(even_nums)) #Output: [2 , 4 , 6 ]
Code language: Python (python)

As you can see from both examples above, filter () is quite flexible and can be used in many different ways.

A python script: filter() Function

class Person: def __init__(self, name, age): self.name = name self.age = age def print(self): print(f'{self.name} ({self.age} years old)') @staticmethod def elder(person): if person.age >= 75: return True return False presidents = [Person('Trump', 80), Person('Putin', 65), Person('Obama', 70), Person('Bush', 75), Person('Clinton', 55), Person('Yeltsin', 65), Person('Nixon', 90)] def elder(person): if person.age >= 75: return True return False if __name__ == '__main__': old_presidents = filter(Person.elder, presidents) for p in old_presidents: p.print()
Code language: Python (python)

Python’s reduce() Function

The reduce () function takes two arguments: a function and an iterable. The function must take two arguments ; It is applied to the first two elements of the iterable, then it is applied to the result of that operation and the third element of the iterable, and so on until only one element remains.

For example :

my_list = [1, 2, 3] result = 0 #step 1: result = 0 + 1 (1) #step 2: result = 1 + 2 (3) #step 2: result = 3 + 3 (6) for num in my_list: result += num print(result) # Output: 6
Code language: Python (python)
from functools import reduce nums = [ 1 , 2 , 3 ] product = reduce((lambda x , y : x * y ), nums ) print(product) # Output: 6
Code language: Python (python)
reduce fuction python

In this example, we wanted to calculate the product all of the numbers in our list so we defined an anonymous lambda function that took two arguments x and y and returned their product .

We then passed that lambda function into our call to reduce along with our list of numbers . As you can see from the output above this code calculated 1 * 2 * 3 which equaled 6. And that’s all there is too it !

These are just some basic examples but hopefully they give you an idea of how these functions work and when they might be useful. experiment with them on your own and see what else you can come up with!

Conclusion:

All three of these functions are incredibly useful for data manipulation and are worth becoming familiar with if you’re doing any sort of data analysis or processing in Python. Thanks for reading!

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts