'Python List of Functions
Is it possible to create a list of functions where you can access them individually? For example:
e=0
def a():
global e
e=1
def b():
global e
e=2
def c():
global e
e=3
l=[a(),b(),c()]
l[2]
print e
l[0]
print e
Output:
>>>3
>>>1
Solution 1:[1]
The problem is that you are calling your functions at the beginning and storing only their values in the list.
e=0
def a():
global e
e=1
def b():
global e
e=2
def c():
global e
e=3
l=[a,b,c]
l[2]()
print e
l[0]()
print e
Output
>>>
3
1
Solution 2:[2]
l=[a(),b(),c()] is not a list of function, rather a collections of values returned from calling those functions. In a list the items are evaluated from left to right, so e is going to be 3 after this step.
As functions are objects in python so you can do:
>>> l = [a, b, c] # creates new references to the functions objects
# l[0] points to a, l[1] points to b...
>>> l[0]()
>>> e
1
>>> l[2]()
>>> e
3
>>> l[1]()
>>> e
2
Solution 3:[3]
As an example: you may change to code to
l=[a,b,c]
l[2]()
print e
l[0]()
print e
and it'll do what you expect. If you declare a list of functions, do not add the parentheses. Instead put them where you call the function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Howard |
