Register to get access to free programming courses with interactive exercises

Built-in map, filter, and reduce Python: Functions

All three higher-level functions we know are build-in in Python. However, map and filter are ready to use, and reduce must be imported from the functools module. Now, we will discuss the differences between each specific function and the simple options we implemented earlier.

The functools.reduce function

Looking at the function declaration, we see:

reduce(function, sequence[, initial]) -> value

Here it is worth paying attention to the fact that the initial value of the accumulator is an optional argument [, initial]. If it is not specified, then reduce will use the first element of the sequence as the initial value. In this case, we remember that the reduce call will result in an error if the sequence is empty.

Let us observe an example of the functools.reduce function:

from functools import reduce

numbers = [2, 3, 8]

def get_maximum(first_num, second_num):
    return first_num if first_num > second_num else second_num

reduce(get_maximum, numbers, 10)  # 10
reduce(get_maximum, numbers, 4)  # 8

The filter function

Now let us take a look at filter:

filter(function or None, iterable) -> filter object

Here is the code:

numbers = [2, 3, 8, 15, 34, 42]

def is_even(num):

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs
profession
new
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.