Use return
instead of print
. When you create your list aa
, each element is being called immediately, because you've written ()
after each element - so consequently each print statement is being run as your list is built. Additinally, when a function doesn't explicitly return a value, it returns None
. When you print(aa[1])
, you're then printing the return value of b(), which is None. So altogether you get:
a # because it's printed in a()
b # because it's printed in b()
c # because it's printed in c()
d # because it's printed in d()
None # because it's returned from b()
If you use return
instead of print
in each function, each element of the list will then contain the value returned by each function (your list would effectively become aa = ['a', 'b', 'c', 'd']
). Then, when you then print(aa[1])
, you'd print the value of aa
in position 1, which would be 'b'
.
def a():
return 'a'
def b():
return 'b'
def c():
return 'c'
def d():
return 'd'
aa=[a(),b(),c(),d()]
print(aa[1])
Alternatively, if you wanted to keep your print statements in each function, you could build your list with references to each function instead of calling each function - and then run the result:
def a():
print ('a')
def b():
print('b')
def c():
print('c')
def d():
print('d')
aa=[a,b,c,d]
print(aa[1]())
By putting ()
after the aa[1]
, you're saying, try to run whatever is returned from aa[1]
. Since aa[1]
contains a reference to function b
, you're effectively calling b()
at that point, which will then run your print('b')
statement.