Python Interactive Guide - Step 3 Functions (8) - Higher-Order Functions
- This course, Python Interactive Guide, is designed to help you learn the basics of Python programming through hands-on, interactive examples.
- The “Style Guide” sections introduce clean coding practices, mainly based on PEP8.
- You can run and experiment with every code example.
Feel free to try things out - reloading the page will reset everything.
This is a continuation of “Step 3 Functions”.
3.7. Higher-Order Functions
In the previous section, we learned how to handle lambda expressions by assigning them to variables. In Python, regular functions can also be assigned to variables as objects, and functions can be returned as return values.
Functions that use functions as inputs or outputs are called higher-order functions.
3.7.1. Functions that Input Functions
In Python, you can create functions that receive other functions as arguments and use those functions internally:
In this example, the apply_function
function receives a function (double
or square
) as an argument and calls that function internally to process the data.
Combined with lambda expressions we learned in the previous section, we can write this more concisely:
Create a function called filter_elements
that takes a list and a “condition function” and extracts only the elements that satisfy the condition.
The condition function takes an element and returns a boolean value (True
/False
).
Sample Solution
3.7.2. Functions that Output Functions (Closures)
In Python, you can also create functions that return other functions:
In this example, the make_multiplier
function takes an argument factor
and returns a new function multiplier
that uses this value for multiplication.
For example, a function generated by make_multiplier(2)
will return the input value multiplied by 2
when called.
This way, the multiplier
function that is generated by make_multiplier
“remembers” the value of the factor
variable from the enclosing scope even after it has been output.
Such an inner function that retains information from its generating function after being output is called a “closure”.
Let’s look at another example of closures:
Using the closure mechanism, you can also create a function that generates a counter without using global variables:
As demonstrated, using the closure mechanism allows you to create “functions with memory” without polluting the global scope.
Create a make_prefixer
function that generates a function to add a specified prefix to strings.
Sample Solution
Create an hp_manager
function that takes an initial HP value and returns a function that manages that HP.
The returned function should take damage amount as an argument and return the remaining HP after taking that damage.
If the HP would go below 0, it should return 0 instead.
Use this function to manage the HP of two different monsters separately.
Sample Solution
3.7.3. Built-in Higher-Order Functions
Python provides several useful built-in functions that can be used as higher-order functions.
Let’s look at some of the most commonly used ones.
The map
Function
The map
function applies a specified function to each element of an iterable and returns the results as an iterator.
- An “iterator” is a type of iterable (object that can be iterated over) that can be traversed only once, making it a “use-once” object.
- If you want to use an iterator multiple times, you should convert it to a list using the
list()
function. - “Generators” that we covered in the generator expressions section are also a type of iterator.
- Like generators, iterators are memory-efficient because they generate values one at a time as needed, rather than generating all results at once.
- We’ll cover iterators in more detail in a later section.
The filter
Function
The filter
function applies a condition function to each element of an iterable and returns an iterator containing only the elements for which the function returns True
:
The sorted
Function
The sorted
function, which we covered in the Lists section, is actually a type of higher-order function.
You can customize the sorting criteria by passing a function to the key
parameter:
Complete the following code to achieve the specified output:
Sample Solution
Summary
In this section, we learned the following key points about higher-order functions in Python:
- Concept of higher-order functions: Functions that use functions as inputs or outputs
- Functions that input functions: How to implement functions that take other functions as arguments and use them for processing
- Functions that output functions (closures): How to create functions that generate and return new functions, and how closures retain information from their generating function
- Built-in higher-order functions: How to utilize Python’s standard higher-order functions like
map()
,filter()
, andsorted()
Mastering higher-order functions allows you to write more flexible and concise code.
In the next section, we’ll learn about “decorators,” which are an application of higher-order functions.