Day 18: Python higher-order functions

by small touch shrimp

Functional programming is now gradually accepted by the majority of development groups. More and more developers begin to use this elegant development mode. The main thing we need to know about using functional programming is that:

  1. What are high order functions?
  2. What are the higher-order functions in Python? How to use it?

Concept of higher order function

In functional programming, we can use functions as freely as variables. A function receives another function as a parameter, which is called a higher-order function.

for instance:

def high_func(f, arr):
    return [f(x) for x in arr]

In the above example, high_func is a higher-order function. The first parameter f is a function, and the second parameter arr is an array. The returned value is a list of all the values in the array after being calculated by the F function. For example:

from math import factorial

def high_func(f, arr):
    return [f(x) for x in arr]

def square(n):
    return n ** 2

# Using python's own mathematical functions
print(high_func(factorial, list(range(10))))
# print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

# Use custom functions
print(high_func(square, list(range(10))))
# print out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

High order functions commonly used in Python

Like java, scala and other languages, many of our commonly used higher-order functions are basically the same. In fact, there are only a few basic higher-order functions that we often use in development, and we can also extend them appropriately based on these functions. Then we will start to introduce several commonly used higher-order functions.


Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

Map the specified sequence according to the function provided, and return the mapped sequence. Define:

map(func, *iterables) --> map object
  • Function ා each element in the sequence needs to perform an operation, which can be an anonymous function
  • *iterables one or more sequences

As in the example above, high_func function, map function is high_func function higher-order version, can pass in a function and multiple sequences.

from math import factorial

def square(n):
    return n ** 2

# Using python's own mathematical functions
facMap = map(factorial, list(range(10)))
# print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

# Use custom functions
squareMap = map(square, list(range(10)))
# print out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

You can see that the same result is output, but unlike Python 2. X, the map class is returned in Python 3. X
, and the former directly returns a list.

We can also pass in multiple sequences using anonymous functions, as follows

# Using anonymous functions
lamMap = map(lambda x: x * 2, list(range(10)))
# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# Incoming multiple sequences
mutiMap = map(lambda x, y: x+y, list(range(10)), list(range(11, 15)))
# print out: [11, 13, 15, 17]


Apply a function of two arguments cumulatively to the items of a sequence,from left to right, so as to reduce the sequence to a single value.

Generally speaking, the reduce function needs to pass in a function with two parameters, and then use this function to traverse the sequence from left to right and generate the result. The definition is as follows:

reduce(function, sequence[, initial]) -> value
  • Function ා function, the operation that each element in the sequence needs to perform, can be anonymous function
  • Sequence - sequence of operations to be performed
  • Initial ා optional, initial parameter

Finally, the calculation result of the return function is the same as the initial parameter type

For example:

# Note that the reduce() function is now in the functools package.
from functools import reduce

result = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])

# print out 15

We can see that the sequence [1, 2, 3, 4, 5] is accumulated by anonymous function.

Set initial value:

# Set the initial parameters:
s = reduce(lambda x, y: x + y, ['1', '2', '3', '4', '5'], "number = ")

# print out: number = 12345

Note that the sequence data type needs to be consistent with the initial parameters.


Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

The filter() function is used to filter the unqualified values in the sequence and return an iterator that generates the iterable items whose function (item) is true. If the function is None, an item that is true is returned. It is defined as follows:

filter(function or None, iterable) --> filter object
  • function or None
  • iterable - sequence to be filtered

for instance:

def boy(n):
    if n % 2 == 0:
        return True
    return False

# Custom function
filterList = filter(boy, list(range(20)))

# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# Custom function
filterList2 = filter(lambda n: n % 2 == 0, list(range(20)))

# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

As we can see above, the data in the list that cannot be divided by 2 is excluded.


Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

By default, the sorted function sorts the sequence in ascending order and returns a new list. You can also customize the key function to sort, or set the reverse parameter to determine whether it is ascending or descending. If reverse = True, it is descending. The function is defined as follows:

def sorted(iterable: Iterable[_T], *,
           key: Optional[Callable[[_T], Any]] = ...,
           reverse: bool = ...) -> List[_T]: ...
  • iterable sequence
  • key can be used to calculate the sorting function.
  • Reverse ා collation, reverse = True descending, reverse = False ascending (default).

For example:

list01 = [5, -1, 3, 6, -7, 8, -11, 2]
list02 = ['apple', 'pig', 'monkey', 'money']

# print out: [-11, -7, -1, 2, 3, 5, 6, 8]

print(sorted(list01, key=abs))
# print out: [-1, 2, 3, 5, 6, -7, 8, -11]

# Default ascending
# print out: ['apple', 'money', 'monkey', 'pig']

# Descending order
print(sorted(list02, reverse=True))
# print out: ['pig', 'monkey', 'money', 'apple']

# Anonymous function sorting
print(sorted(list02, key=lambda x: len(x), reverse=True))
# print out: ['monkey', 'apple', 'money', 'pig']


Above we briefly introduced the use of several commonly used higher-order functions, of course, there are many higher-order functions that we can study, such as zip function, etc. I hope the introduction of this section will help you.

Code address

Example code: Python-100-days-day018

Pay attention to the official account: python technology, reply to "python", learn and communicate with each other.

Tags: Python Lambda Programming Java

Posted on Sun, 24 May 2020 05:43:49 -0400 by johnbruce