Day 11: Higher order function (map, filter and reduce)

On Day 11, we learned about higher order functions in programming, specifically the map, filter and reduce functions.

Untitled

1. Introduction

In programming, higher order functions are functions that take other functions as arguments or return functions as results. This is a powerful concept that enables a lot of flexibility and expressiveness in code. In this post, we'll explore three important higher order functions in Python: map, filter, and reduce.

2. map, filter and reduce

2.1 Map

The map function is used to apply a function to each element of an iterable, such as a list or a tuple, and return a new iterable with the transformed values. Here's the syntax:

map(function, iterable)

The map function returns an iterator that generates the transformed values lazily, which means that it only computes the next value when needed. For example, let's say we have a list of numbers that we want to double:

numbers = [1, 2, 3, 4, 5]
doubled = map(lambda x: x * 2, numbers)
print(list(doubled)) # [2, 4, 6, 8, 10]

In this example, we used a lambda function to define the doubling operation. The map function applies this function to each element of the numbers list and returns an iterator that generates the transformed values.

2.2 Filter

The filter function is used to select some elements of an iterable based on a given function that tests each element. Here's the syntax:

filter(function, iterable)

The filter function returns an iterator that generates the elements for which the given function returns True. For example, let's say we have a list of numbers and we want to select only the even ones:

numbers = [1, 2, 3, 4, 5]
even = filter(lambda x: x % 2 == 0, numbers)
print(list(even)) # [2, 4]