Jul-03-2020, 05:55 PM
What you've learnt here is that functions can be treated as values in Python and so can be passed around to other functions. This is quite a useful, powerful idea, because it means you can build quite generic functions that can be reused in different ways, by passing in different functions. That seems a bit abstract, so let's look at some examples:
Let's say I have a list of numbers and I want to double each of them, or I have a list of strings and want to turn them into uppercase. The thing in common here is wanting to do something to each item in the list; it's just that the "something" varies. The
1. Using
2. I have to call
This idea of higher order functions (those that either take functions as arguments, or return them) is quite commonplace in many programming languages today.
Let's say I have a list of numbers and I want to double each of them, or I have a list of strings and want to turn them into uppercase. The thing in common here is wanting to do something to each item in the list; it's just that the "something" varies. The
map
function is the kind of generic function I'm talking about. It takes a list (or other iterable) and a function to call on each item:>>> values = [1, 2, 3, 4] >>> def double(x): ... return 2 * x ... >>> list(map(double, values)) [2, 4, 6, 8] >>> words = ["hello", "goodbye", "dog", "cat"] >>> def uppercase(word): ... return word.upper() ... >>> list(map(uppercase, words)) ['HELLO', 'GOODBYE', 'DOG', 'CAT'] >>>A couple things to note here:
1. Using
map
might not be considered the most idiomatic Python - normally I'd use a list comprehension for these but I'm specifically using map
to illustrate the point.2. I have to call
list
on the return value of map
because it doesn't return a list, but rather a kind of lazy sequence. Essentially that means that each of the items in that sequence is computed on demand when it's accessed, so printing the object you get back wouldn't be much use.This idea of higher order functions (those that either take functions as arguments, or return them) is quite commonplace in many programming languages today.