Skip to content

Map, Filter & Reduce

These are higher-order functions from functional programming that provide concise ways to process iterables. They are often used with anonymous lambda functions.

  • map(): Applies a function to every item in an iterable and returns a new iterable with the transformed results. It’s used for transformation.

    nums = [1, 2, 3, 4]
    doubled_nums = list(map(lambda x: x*2, nums))
    print(doubled_nums) # Output: [2, 4, 6, 8]
  • filter(): Creates a new iterable with items from the original iterable that satisfy a certain condition (i.e., the function returns True). It’s used for selection.

    nums = [1, 2, 3, 4]
    even_nums = list(filter(lambda x: x % 2 == 0, nums))
    print(even_nums) # Output: [2, 4]
  • reduce(): Applies a function cumulatively to the items of an iterable, reducing it to a single value. This function is found in the functools module. It’s used for aggregation.

    from functools import reduce
    nums = [1, 2, 3, 4]
    sum_nums = reduce(lambda x, y: x + y, nums)
    print(sum_nums) # Output: 10