Search⌘ K
AI Features

Functional Tools: map() and filter()

Explore how to use Python's map() and filter() functions to process data by applying transformations or filtering items selectively. Learn to write modular, memory-efficient code using functions and lambda expressions, and understand when to choose functional tools over list comprehensions.

We have already mastered loops and comprehensions to process lists. However, Python supports another powerful paradigm borrowed from functional programming: separating the action (a function) from the iteration (the loop). Instead of writing a loop that manually calls a function on every item, we can simply tell Python, "Map this function over a list." This approach emphasizes modularity and composability, allowing us to treat functions as reusable components in a data processing pipeline.

Transforming data with map()

The map() function applies a specific function to every item in an iterable. It takes two primary arguments, the function to apply and the iterable containing the data, as follows:

map(function, iterable)

Crucially, map() does not create a new list. Instead, it returns a map object, i.e., an iterator that produces results one by one as needed. This "lazy evaluation" is efficient in terms of memory, but if we want to see all ...