How to Pass a Function as a Callback to map and filter in Python

Shows how to apply custom functions to every element of a list using map and filter callbacks in Python.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 16 views 0 copies

Python code

13 lines
Python 3.9+
def double(x):
    return x * 2

def is_even(x):
    return x % 2 == 0

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    doubled = list(map(double, numbers))
    evens = list(filter(is_even, numbers))
    print("Original:", numbers)
    print("Doubled:", doubled)
    print("Evens:", evens)

Output

stdout
Original: [1, 2, 3, 4, 5]
Doubled: [2, 4, 6, 8, 10]
Evens: [2, 4]

How it works

map and filter accept a function as their first argument and apply it to an iterable. map transforms each item with the callback, while filter keeps only items where the callback returns truthy. Both return lazy iterators, so wrapping them in list() materializes the results. This functional style avoids manual loops and makes the transformation intent clear.

Common mistakes

  • Calling the function with parentheses (e.g., map(double(), numbers)) instead of passing the function reference
  • Forgetting that map and filter return iterators, not lists, and skipping list() conversion
  • Using filter on the result without a predicate that returns a boolean

Variations

  1. Use lambda expressions: list(map(lambda x: x * 2, numbers))
  2. Use a list comprehension: [x * 2 for x in numbers] or [x for x in numbers if x % 2 == 0]

Real-world use cases

  • Transforming raw API response fields (e.g., converting string prices to floats) in a batch before aggregation.
  • Filtering out empty or invalid records from a dataset before writing to a database.
  • Applying a unit-conversion function to temperature readings coming from multiple IoT sensors.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.