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.
def function1(): print('Function 1') def function2(): print('Function 2') myList = [function1, function2]
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.
def function1(): print('Function 1') def function2(): print('Function 2') #list of functions myList = [function1, function2] #call function using list object myList() myList()
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.
In this tutorial of Python Examples, we learned how to define a list with functions as items, and how to work with them.
- Python List without Last Element
- How to Access List Items in Python?
- Python – Check if List Contains all Elements of Another List
- Python List of Lists
- How to Append List to Another List in Python? – list.extend(list)
- Python – Get Index or Position of Item in List
- Python List of Dictionaries
- How to Reverse Python List?
- Python List – Add Item
- Python – Convert List to Dictionary