Grazes
Grazes

Reputation: 23

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

Upvotes: 2

Views: 2239

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

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

Upvotes: 4

jamylak
jamylak

Reputation: 133554

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

Upvotes: 7

Howard
Howard

Reputation: 39197

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.

Upvotes: 0

Related Questions