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:
- Use
map,filter, andreducetogether to perform cumulative operations on filtered data. - Combine
mapandsortedto 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:
- Filtering the even numbers.
- Squaring these even numbers.
- 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:
