40

can I call a list of functions and use list comprehension?

def func1():
    return 1

def func2():
    return 2

def func3():
    return 3

fl = [func1, func2, func3]

fl[0]()
fl[1]()
fl[2]()

I know I can do

for f in fl:
    f()

but can I do below ?

[f() for f in fl]

A additional question for those kind people, if my list of functions is in class, for example

class F:
    
    def __init__(self):
        self.a, self.b, self.c = 0, 0, 0
        
    def func1(self):
        self.a += 1

    def func2(self):
        self.b += 1

    def func3(self):
        self.c += 1

    fl = [func1, func2, func3]

fobj = F()

for f in fobj.fl:
    f()

does it work?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Jerry Gao
  • 1,389
  • 3
  • 13
  • 17

4 Answers4

31
>>> [f() for f in fl]
[1, 2, 3]

Absolutely :)

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
19

Of course you can as Fábio Diniz said :)

However for the class method when used as a callable, an object must be given as an argument:

fobj = F()

for f in fobj.fl:
    f(fobj)

The object must be given as an argument to the callable because when you look at the definition of the method def funcX(self): the method needs one argument self

wjandrea
  • 28,235
  • 9
  • 60
  • 81
P2bM
  • 1,038
  • 6
  • 9
  • 1
    How do I do this if I need to pass arguments to the functions? – vipulnj Apr 24 '19 at 22:38
  • That's an odd approach. I think it'd make more sense to move `fl` into `__init__`, i.e. `self.fl = [self.func1, self.func2, self.func3]`. Then you don't need to pass the instance to `f`. But then, it's not clear what OP's trying to accomplish exactly, so who knows. – wjandrea Mar 13 '23 at 20:14
1

Yes, you can. The resultant list will hold the return values of your functions.

nmichaels
  • 49,466
  • 12
  • 107
  • 135
0

Yes, you can - the functions get called as intended.

Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122