Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call list of function using list comprehension

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?

like image 590
Jerry Gao Avatar asked Mar 28 '11 15:03

Jerry Gao


People also ask

Can I call function in list comprehension?

Answer. Yes, the variable in the for of a list comprehension can be used as a parameter to a function.

How a list can be created using list comprehension?

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.

Is Python list comprehension functional?

List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.


2 Answers

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

Absolutely :)

like image 59
Mike Lewis Avatar answered Sep 29 '22 23:09

Mike Lewis


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"

like image 31
P2bM Avatar answered Sep 29 '22 22:09

P2bM