🐍

map(), filter() and reduce()

Programare Python Advanced 5 min read

map(), filter() and reduce()

map(function, iterable)

Applies function to each element:

squares = list(map(lambda x: x**2, [1, 2, 3]))  # [1, 4, 9]

filter(function, iterable)

Keeps elements where function returns True:

evens = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4]))  # [2, 4]

reduce(function, iterable)

Reduces to single value (from functools):

from functools import reduce
total = reduce(lambda a, b: a + b, [1, 2, 3, 4])  # 10

Key Points

  • All return iterators (use list())
  • Comprehensions often clearer
  • filter(None, ...) removes falsy values

📚 Related Articles