Using list comprehension how to call list of function

0 votes

Can i use list comprehension and call list of function?

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?

Nov 14, 2018 in Python by Jino
• 5,820 points
3,747 views

1 answer to this question.

0 votes

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

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"

fobj= F()

for f in fobj.fl:
    f(fobj)
answered Nov 14, 2018 by Theodor
• 740 points

Related Questions In Python

+1 vote
4 answers

how to sort a list of numbers without using built-in functions like min, max or any other function?

Yes it is possible. You can refer ...READ MORE

answered Jun 27, 2019 in Python by Arvind
• 3,050 points
188,462 views
0 votes
1 answer

How to get the multiplication table of any number using list comprehension?

Hey @Neha, you can use something like ...READ MORE

answered Jul 8, 2019 in Python by Sakshi
6,678 views
0 votes
4 answers

How to print objects of class using print function in Python?

>>> class Test: ... ...READ MORE

answered Dec 16, 2020 in Python by Roshni
• 10,480 points
78,510 views
+1 vote
1 answer

how to run list of functions using Thread?

You could import the file with function ...READ MORE

answered Aug 26, 2019 in Python by Vishaka
1,598 views
0 votes
1 answer

How to sort a list of strings?

Basic answer: mylist = ["b", "C", "A"] mylist.sort() This modifies ...READ MORE

answered Jun 4, 2018 in Python by aryya
• 7,460 points
1,497 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
0 votes
1 answer

Using Python what kind of applications can be built?

http://en.wikipedia.org/wiki/List_of_Python_software  follow the link and You will see ...READ MORE

answered Nov 14, 2018 in Python by Theodor
• 740 points
838 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP