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.
Python code
13 linesdef 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
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
- Use lambda expressions: list(map(lambda x: x * 2, numbers))
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.