2

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

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

Worthy of note: the reason this works is because functions are first class objects in Python. When you refer to a, b, and c this way, you're using variables of those names that happen to contain functions. You can even reassign them.
4

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.