Higher Order Functions and Map
In this tutorial, you'll learn about higher order functions in Python, including how to use them with lambda functions and the built-in map
function. Discover how these concepts can simplify your code and make it more efficient.
Let's talk about higher order functions.
A higher order function is a function that either takes one or more functions as arguments, or returns a function as its result.
Here's a simple example:
The function apply_function
takes another function func
and a value as arguments.
It then applies the function to the value and returns the result.
Let's see how this works in practice:
When we call apply_function(square, 5)
, we are passing the square
function as an argument to apply_function
along with the value 5
. The apply_function
then executes square(5)
, which calculates 5 * 5
and returns 25
.
While this approach works, it may not immediately seem useful. After all, we could achieve the same result by calling square(5)
directly.
Let's adjust our higher order function a bit:
Now, instead of applying a given function to a single value, apply_function
applies the function to each item in a list.
Let's see how this works in practice:
Now the apply_function
applies square
to each item in [1, 2, 3, 4, 5]
.
Now, this is more useful. However, it might feel a bit complex—so let’s simplify it.
Instead of defining a separate square
function, we can use a lambda function directly within the apply_function
call:
What will be the output?
We can use the apply_function
function to apply different functions to all items of a list.
This is a common use case in programming, which is why Python has a built-in function for this purpose: map
.
The map
function allows you to apply a function to every item in an iterable (like a list).
Here's how our square example looks when using map
:
One thing to note is that the map function doesn't directly return the list of results. Instead it returns a map object.
A map object is an iterator, a concept we'll cover later.
However, you can easily transform the map object into a list using the list
method.
Let's apply this to our example:
Or in one line of code:
See how we drastically simplified our code using the map
function together with a lambda function? We achieved the same result using a single line of code.
What will be the output?
What will be the output?