Store Functions in List and Call in Python
In Python, a list of functions can be created by defining the tasks and then adding them to a list. Here’s a simple example to illustrate how to do this:
def say_hello():
return "Hello!"
#Store a function "say_hello" in a list
greetings = [say_hello]
#Call the first function in the list
print(greetings[0]())
Output
Hello!
Let's Explore some other methods to store functions and call them in lists.
Table of Content
Calling Functions with Arguments from a List
Functions can also accept arguments. You can store functions that take parameters in a list and pass the necessary arguments when calling them.
def add(a, b):
return a + b
#Stores the 'add' functions
operations = [add]
#calls function stored at index 0
#pass argumemts 10 and 5 to the 'add' function
result = operations[0](10, 5)
print("Addition:", result)
Output
Addition: 15
The add
function is stored in the operations list, and it's called using indexing with arguments 10 and 5 to perform the addition.
Dynamic Function Call Using Loops
Using loops to call functions simply allows us to iterate over the list and execute each function dynamically without needing to call them one after the other.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
#it stores the add and subtract functions
operations = [add, subtract]
a, b = 8, 2
#use a loop to call each function
for func in operations:
print(func(a, b))
Output
10
The list operations
stores two functions, add
and subtract and t
he for
loop goes through each function in the list and calls it with the same argument (a = 8
, b = 2
).
Using List Comprehension to Call Functions
We can use list comprehension to call functions stored in a list and store their results in a new list. This method makes the code more compact and readable when dealing with simple function calls.
def add(a, b):
return a + b
# Create a list called 'operations' that stores
#the add and subtract functions
operations = [add]
results = [func(10, 5) for func in operations] # use list comprehension to call each function with arguments
print("Results:", results)
Output
Results: [15]
By iterating over the list, each function is invoked with the specified arguments, and the results are stored in a new list.
Storing Lambda Functions in a List
Lambda functions can be stored in a list just like normal functions, which is dynamic and allows flexible execution without explicitly naming the functions.
operations = [lambda x, y: x * y]
# Calls the multiplication lambda function
result = operations[0](6, 3)
print("Multiplication:", result)
Output
Multiplication: 18
It demonstrate about lambda functions can be stored in a list and called through indexing. It stores a multiplication lambda function in the list and then calls it with the respective arguments, outputting the result.