In Python, functions are first-class objects, which means they can be stored in lists and dictionaries just like any other object. This allows you to create lists or dictionaries of functions, which can be used to call multiple functions with the same input parameters or to choose a specific function to call based on some condition.
Here's an example of storing functions in a list:
def add(a, b): return a + bdef subtract(a, b): return a - bdef multiply(a, b): return a * bdef divide(a, b): return a / bmath_functions = [add, subtract, multiply, divide]result = math_functions[0](4, 2) # result = 6 |
In this example, we define four math functions and store them in a list called math_functions. We can then use the list to call the functions with different input parameters. In this case, we call the first function in the list (add) with input parameters 4 and 2, which returns 6.
Here's an example of storing functions in a dictionary:
def add(a, b): return a + bdef subtract(a, b): return a - bdef multiply(a, b): return a * bdef divide(a, b): return a / bmath_functions = { "addition": add, "subtraction": subtract, "multiplication": multiply, "division": divide}result = math_functions["addition"](4, 2) # result = 6 |
In this example, we define the same four math functions and store them in a dictionary called math_functions. We can then use the dictionary to call the functions by their keys. In this case, we call the function with key "addition" with input parameters 4 and 2, which returns 6.
In summary, storing functions in lists and dictionaries allows you to call multiple functions with the same input parameters or choose a specific function to call based on some condition. This feature is a powerful tool that can simplify code and make it more modular.