Python map, filter, reduce, and find: A Practical Guide with Examples

Python map, filter, reduce, and find: A Practical Guide with Examples

Loops are fine, but Python’s map, filter, reduce, and find let you express the same logic in one expressive line — and make your intent obvious to the next reader. If you’ve ever written a five-line for loop just to transform a list, this guide will save you a lot of keystrokes.

This article walks through each function with realistic examples, shows the lambda shortcut for each one, and ends with a comparison table so you always know which tool to reach for.

The example dataset

We’ll use a list of fruit dictionaries throughout. Realistic enough to feel like real data, simple enough to keep examples short:

fruits = [
    {"name": "Apple",  "units": 3, "price": 0.25},
    {"name": "Mango",  "units": 6, "price": 0.35},
    {"name": "Banana", "units": 4, "price": 0.15},
]

map(): transform every item

map() returns a new iterable where each item is the result of applying a function to the original. Use it when every input produces exactly one output.

When to use this: turning one list into another of the same length — e.g., formatting, computing a derived value, or extracting a field.

def summary_func(fruit: dict) -> str:
    cost = fruit["price"] * fruit["units"]
    return f'{fruit["units"]} units of {fruit["name"]} costs ${cost:.2f}'

summary = list(map(summary_func, fruits))
# ['3 units of Apple costs $0.75',
#  '6 units of Mango costs $2.10',
#  '4 units of Banana costs $0.60']

# Lambda equivalent for short transforms:
names = list(map(lambda f: f["name"], fruits))
# ['Apple', 'Mango', 'Banana']

Tip: for simple transforms, a list comprehension ([f["name"] for f in fruits]) is often considered more Pythonic than map. Use map when you already have a named function.

filter(): keep only items that match

filter() returns a new iterable containing only the items for which the predicate returns truthy.

When to use this: narrowing down a list — e.g., active users, items in stock, errors above a threshold.

def cheap(fruit: dict) -> bool:
    return fruit["price"] < 0.20

cheap_fruits = list(filter(cheap, fruits))
# [{'name': 'Banana', 'units': 4, 'price': 0.15}]

# Lambda equivalent:
cheap_fruits = list(filter(lambda f: f["price"] < 0.20, fruits))

find: get the first item that matches

Python doesn’t have a built-in find() — the idiomatic way is next() with a generator expression and a default value. This is significantly more efficient than filtering a whole list when you only need one match.

When to use this: looking up a single item — e.g., a user by ID, the first error in a log.

search = "mango"
mango = next(
    (f for f in fruits if search in f["name"].lower()),
    None,  # default if not found
)
# {'name': 'Mango', 'units': 6, 'price': 0.35}

reduce(): collapse a list into a single value

functools.reduce() applies a two-argument function cumulatively to the items of an iterable, reducing it to a single value.

When to use this: totals, products, building a single object from many — when there’s no built-in (sum, min, max, any, all) that already does the job.

from functools import reduce

def add_cost(acc: float, fruit: dict) -> float:
    return acc + fruit["price"] * fruit["units"]

grand_total = reduce(add_cost, fruits, 0)
# 3.45

# Lambda equivalent:
grand_total = reduce(lambda acc, f: acc + f["price"] * f["units"], fruits, 0)

# But for plain sums, prefer:
grand_total = sum(f["price"] * f["units"] for f in fruits)

Quick comparison

FunctionInputOutputUse when
mapiterableiterable (same length)Transforming each item
filteriterableiterable (≤ same length)Keeping items that match
next (find)iterablesingle item or defaultFirst match only
reduceiterablesingle valueAggregating into one result

Should you always use these?

In modern Python, list comprehensions and generator expressions are often clearer than map and filter. For aggregations, prefer sum, min, max, any, all, or statistics functions over reduce. Reach for these functional tools when:

  • You already have a named function to apply (no need to inline logic in a comprehension).
  • You’re working with very large iterables and want lazy evaluation.
  • You’re writing in a functional style for consistency with the rest of the codebase.

Final thoughts

Once map, filter, find, and reduce click, you’ll start seeing them everywhere — they’re a vocabulary for describing data transformations clearly. Pair them with comprehensions, and you’ll write less code with more intent.

Looking for the JavaScript equivalents? See JavaScript useful array functions: map, filter, find and reduce. The full snippet for these examples is on GitLab.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Pin It on Pinterest

0
Would love your thoughts, please comment.x
()
x