Python List of Functions

Python List of Functions

In Python, Function is a first-class object which means that function is just like any other object.

A function can be passed as argument, or you can include a function as an item in a list, or as a value in key:value pair of a dictionary, or item in a set, etc.

In this tutorial, we will learn how to add function(s) as item(s) in a list. In other words, we will build a list of functions.

Example 1: List of Functions

In this example, we define two functions named function1() and function2(). Then we will initialize a list with these two functions as items.

Python Program

def function1():
    print('Function 1')

def function2():
    print('Function 2')

myList = [function1, function2]
Run

We can also use the items of the list, which are functions, and call them. In the following program, we will use these list items and call the functions.

Python Program

def function1():
    print('Function 1')

def function2():
    print('Function 2')

#list of functions
myList = [function1, function2]

#call function using list object
myList[0]()
myList[1]()
Run

Output

Function 1
Function 2

Note: Parenthesis after the function name calls the function, while just the function name gets the reference to the function.

Keeping in mind the above note, observe the Python program we wrote for this example. When we added functions to the list as items, we have not mentioned any parenthesis, just the function names. And when we wanted to call the function, we fetched the functions from the list using index, and used parenthesis. Parenthesis after function name called the function and executed it.

Summary

In this tutorial of Python Examples, we learned how to define a list with functions as items, and how to work with them.