MyInternships.in

Python Functions

Python map filter and reduce

map, filter and reduce are functional-programming tools that let you transform, select and combine items in an iterable like a list, often paired with a short lambda function.


map() — Transform Every Item

map(function, iterable) applies a function to every item in an iterable and returns a map object (wrap it with list() to see the results). It is a quick way to transform data without writing an explicit loop.

map with lambda
Python
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)   # [2, 4, 6, 8]

filter() — Keep Matching Items

filter(function, iterable) keeps only the items for which the function returns True, throwing away everything else. The function passed in should return a boolean.

filter with lambda
Python
nums = [1, 2, 3, 4, 5, 6, 7, 8]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)   # [2, 4, 6, 8]

reduce() — Combine Into One Value

reduce(), found in the functools module (not built-in like map and filter), repeatedly applies a function to pairs of items until the whole iterable collapses into a single value, such as a running total or product.

reduce with lambda
Python
from functools import reduce

nums = [1, 2, 3, 4]
total = reduce(lambda acc, x: acc + x, nums)
print(total)   # 10 -> ((1+2)+3)+4
ℹ️

reduce needs "from functools import reduce" first — unlike map and filter, it is not automatically available.

Chaining Them Together

These three tools can be combined: filter out unwanted items, transform what remains with map, then collapse the result with reduce.

Python
from functools import reduce

nums = [1, 2, 3, 4, 5, 6]
result = reduce(lambda a, b: a + b,
                map(lambda x: x * x,
                    filter(lambda x: x % 2 == 0, nums)))
print(result)   # squares of evens (4+16+36) = 56

map/filter vs List Comprehensions

Most Python developers prefer list comprehensions over map and filter for everyday tasks, because they read more like plain English and avoid extra lambda syntax. map and filter are still useful for functional-style pipelines or when passing an existing named function.

Taskmap/filter + lambdaList comprehension
Double every numberlist(map(lambda x: x*2, nums))[x*2 for x in nums]
Keep even numberslist(filter(lambda x: x%2==0, nums))[x for x in nums if x%2==0]
ReadabilityExtra lambda syntaxUsually more Pythonic
Best forFunctional pipelines, named functionsEveryday filtering/transforming
💡

PEP 8 and most style guides favour list comprehensions for simple cases — reach for map/filter/reduce mainly when you already have a reusable function to pass in, or when chaining functional operations.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships