Functions as Objects in Python
One of the most powerful features of Python is that everything is an object, including functions. Functions in Python are first-class objects.
This broadly means, that functions in Python:
- have types
- can be sent as arguments to another function
- can be used in expression
- can become part of various data structures like dictionaries
Sending functions as arguments coupled with the ability to store them in lists can be extremely helpful. I know all of this can be hard to digest so let’s take this step by step.
Functions can be passed as arguments
For the rest of the tutorial, we will define an ‘apply’ function which will take as input a list, L and a function, f and apply the function to each element of the list. This example has been taken from the Edx Course 6.00.1.x.
Let’s see how we can call this function:
L = [1, -2, -5, 6.2]print apply(L, abs) # [1…