1. Map, Filter, and Reduce

This article is participating in Python Theme Month,See the activity link for details

These three functions help with the functional programming approach. We’ll discuss them one by one and learn about their use cases.

In most cases, we want to pass all the list elements to the function and collect the output. Such as:

items = [1.2.3.4.5]
list1 = []
for i in items:
    list1.append(i**2)
Copy the code

Map allows us to do this in a simpler and better way.

items = [1.2.3.4.5]
squared = list(map(lambda x: x**2, items))
Copy the code

Most of the time we use lambda expressions, and maps can do the same. We could even have a list of functions.

def multiply(x) :
    return (x*x)
def add(x) :
    return (x+x)

funcs = [multiply, add]
for i in range(5):
    value = list(map(lambda x: x(i), funcs))
    print(value)

# Output:
# [0, 0]
# [1, 2]
# (4, 4)
# [9, 6]
By the # [8]
Copy the code

4.2. The Filter

As the name implies, filter creates a list of elements whose function returns true. Here’s a short and concise example:

number_list = range(-5.5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)

# Output: [-5, -4, -3, -2, -1]
Copy the code

The filter is similar to the for loop, but it is a built-in function and faster.

Note: If maps and filters aren’t pretty to you, you can read list/dict/tuple to understand.

4.3 the Reduce

Reduce is a very useful function for performing some calculation on a list and returning the result. It applies scrolling calculations to successive pairs of values in a list. For example, if you want to compute the product of a list of integers.

Therefore, the normal way for you to perform this task in Python is to use the basic for loop:

product = 1
list = [1, 2, 3, 4]
for num in list:
    product = product * num

# product = 24
Copy the code

Now let’s try reduce:

from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])

# Output: 24
Copy the code