Combining Functions

Lesson Introduction

Welcome to this lesson on combining functions in Python! By now, you should already be familiar with map, filter, reduce, and sorted from our previous lessons. Combining these functions lets you perform powerful data transformations concisely and readably.

Lesson Goals

By the end of this lesson, you'll understand how to combine multiple higher-order functions to perform complex data processing tasks. Specifically, we'll cover how to:

  1. Use map, filter, and reduce together to perform cumulative operations on filtered data.
  2. Combine map and sorted to achieve custom ordering of processed data.

These skills will help you write more efficient and readable code.

Combining map, filter, and reduce Functions

Let's solve a simple problem: finding the sum of the squares of even numbers from a list. We'll break this into three steps:

  1. Filtering the even numbers.
  2. Squaring these even numbers.
  3. Summing the squared values.

We'll use Python's filter, map, and reduce functions.

Filtering Even Numbers

Use the filter function to extract even numbers. filter takes two arguments: a function and an iterable. It only keeps items for which the function returns True.

Example:

numbers = [5, 1, 9, 3, 7, 8, 6, 2, 4, 0]

# Define a lambda function to check even numbers
is_even = lambda x: x % 2 == 0

# Use filter to extract even numbers
even_numbers = list(filter(is_even, numbers))
print(even_numbers)  # [8, 6, 2, 4, 0]

Mapping to Squares and Reducing to a Sum

Use the map function to square each filtered even number. map also takes two arguments: a function and an iterable.

Example:

# Define a lambda function to square numbers
square = lambda x: x ** 2

# Use map to square even numbers
squared_numbers = list(map(square, even_numbers))
print(squared_numbers)  # [64, 36, 4, 16, 0]

Finally, use the reduce function from the functools module to sum the squared values. reduce takes a function and an iterable, and applies the function cumulatively.

Example:

from functools import reduce

# Define a lambda function to sum numbers
sum_numbers = lambda acc, x: acc + x

# Use reduce to sum the squared numbers
sum_of_squares = reduce(sum_numbers, squared_numbers)
print(sum_of_squares)  # 120
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal