Higher Order Functions in Python

Also known as first-class functions, functions can take other functions as parameters and also return other functions.

Since everything in Python is an object, we can treat functions as such.

Say you have a list of car brands that is totally messy and you want to normalize them.

The task is for all of them to be lower case, no extra spaces at the beginning or end of each brand name.

One way to do that is to use the special functions built-in Python to handle strings.

strip() will remove the extra spaces, lower() will convert all the characters into lower case

We are going to define a function that takes a list, iterates over the values, and applies the cleaning to each of them.

Then we take each new normalized value and add it to a new list normalized_brands that will be returned as a result of our function execution.

car_brands = ['BMW ', 'Ferrari', 'McLareN', ' TOyota', '   Ford   ']

def normalize_brands(brand_list):
     normalized_brands = []
     for brand in brand_list:
             brand = brand.strip()
             brand = brand.lower()
             normalized_brands.append(brand)
     return normalized_brands

car_brands_normalized = normalize_brands(car_brands)

print(car_brands_normalized)
['bmw', 'ferrari', 'mclaren', 'toyota', 'ford']

It works as expected, but this function is very useful and could be refactored to be more generalist.

Functions can also be treated as objects, meaning we can have things like a list of functions!

Then we can iterate over them and apply the values in a more dynamic fashion, let\’s see that in action to make it more clear.

car_brands = ['BMW ', 'Ferrari', 'McLareN', ' TOyota', '   Ford   ']

normalization_functions = [str.strip, str.lower]

def normalize_strings(string_list, functions):
     normalized_strings = []
     for item in string_list:
             for func in functions:
                     item = func(item)
             normalized_strings.append(item)
     return normalized_strings

normalized_brands = normalize_strings(car_brands, normalization_functions)

print(normalized_brands)
['bmw', 'ferrari', 'mclaren', 'toyota', 'ford']

We have a list of strings as before, but now we also have a list of functions.

Our function normalize_strings now expects both lists, the strings, and the functions list.

We create a new empty list to store our normalized strings.

Then the first for loop goes through each item in string_list and the second for loop goes through each item in functions.

Then we apply each func to each item by calling item = func(item).

Then we add the new normalized item to our new list and when it finishes, we return normalized_strings.

This way we can increase normalization_functions to have as many functions as we need and reuse normalize_strings(string_list, functions) in many other situations.

Watch on Youtube

You can also watch this content on Youtube: