Find out our product. Here!

Functions as Data part 2 - FP Series

Explore the versatility of first-class functions in Python. Learn how to create and use a list of functions for efficient data transformations.
image_title

In this post, we'll explore another fascinating aspect of first-class functions. Just like you can create lists of other data types, such as numbers or strings, because functions in Python are first-class, we can also create a list of functions.

Now, you might be wondering why we'd want to do something like that. Well, let's say we have several different functions we've created, each designed to modify an argument in some way, like doubling it or subtracting from it.

And now, let's imagine we want to obtain the result of applying all these functions to a number.

The conventional way to do this would be something like:


my_number = 3
my_number = double(my_number)
my_number = minus_one(my_number)
my_number = squared(my_number)
print(my_number)

But what if we had hundreds or even thousands of these transformation functions to apply to a given variable? In that case, we can define a list containing all these functions:


function_list = [
    squared,
    double,
    minus_one,
    math.sqrt,
]

Notably, when placing functions into the list, we don't include parentheses after them, unlike what you might be used to.

This is a concept to grasp in functional programming. Parentheses are used when calling a function to obtain its result. When referring to the function itself, we use the function's name without parentheses.

Now, with our list of functions, we can iterate through them and apply each one to our number, like so:


for func in function_list:
    my_number = func(my_number)

print(my_number)

While this code involves some procedural aspects and mutation, it serves as an introductory example. Later in the course, we'll explore a more functional approach.

Feel free to experiment with the order of functions or even include Python's math functions in your list. You can import the math module and add functions like math.sqrt to further explore this concept.

Read Also :
Holla, we share any interesting view for perspective and education sharing❤️

Post a Comment

© elgharuty. All rights reserved. Developed by Jago Desain