...

/

Higher-Order Functions

Higher-Order Functions

Learn about the usage of some higher-order functions in Python.

A higher-order function is a function that can receive other functions as arguments or return them.

For example, we can pass a lambda function to the built-in sorted() function to sort a dictionary by values instead of keys.

Press + to interact
d = {'Oil' : 230, 'Clip' : 150, 'Stud' : 175, 'Nut' : 35}
# lambda takes a dictionary item and returns a value
d1 = sorted(d.items( ), key = lambda kv : kv[1])
print(d1) # prints [('Nut', 35), ('Clip', 150), ('Stud', 175), ('Oil', 230)]

The sorted() function uses a parameter key. It specifies a function of one argument that is used to extract a comparison for each element in the first argument of the sorted() function. The default value of the key is None, indicating that the elements in the first argument are to be compared directly.

To facilitate functional programming, Python provides three higher-order functions—map(), filter(), and reduce(). Before we see how to use these functions, we need to understand these operations.

The map, filter, and reduce operations

A map operation applies a function to each element in the sequence, like a list, tuple, etc., and returns a new sequence containing the results. For example:

  • Finding the square root of all numbers in the list and returning a list of these roots.
  • Converting all characters in the list to uppercase and returning the uppercase characters list.

A filter operation applies a function to all the elements of a sequence. A sequence of those elements for which the function returns True is returned. For example:

  • Checking whether each element in a list is an alphabet and returning a
...