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:

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:

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:

Full Example

The beauty of functional programming shines when you combine all these steps into one streamlined operation.

This code is concise and efficient. The nested function calls allow you to keep the program short.

Combining with Sorting

Let's sort the squared values of even numbers in descending order. Combine filtering, mapping, and sorting operations.

The sorted function allows custom sorting criteria. To sort in descending order, use the reverse=True parameter.

Example:

Lesson Summary

Congratulations! You've learned how to combine higher-order functions in Python to perform complex data transformations. Here's a quick summary of what we've covered:

  1. Combining filter, map, and reduce: We filtered even numbers, squared them, and then summed the squared values.
  2. Combining with sorting: We sorted the squared even numbers in descending order.

These combinations let you handle diverse data processing tasks efficiently.

Now it's time to apply your knowledge in hands-on exercises. You'll get to combine these functions and tackle various data processing challenges. Happy coding!

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