Sergio A. Quiroga
Sergio A. Quiroga

Reputation: 11

list of function with several parameters python

I'm trying to implement a list of the same function called with different parameters, something like this:

def func1(num):
    print("{}".format(num))

fl = [func1(1),func1(2),func1(3)]

for f in fl: 
    fl()

i got an error saying that 'list' object is not callable.

now, this works:

def func1():
    print 1
def func2():
    print 2
def func3():
    print 3

fl = [func1,func2,func3]

for f in fl:
   f()

what am i doing wrong?

Upvotes: 0

Views: 50

Answers (3)

ForceBru
ForceBru

Reputation: 44828

Use functools.partial:

from functools import partial

functions = [partial(func1, i) for i in range(1, 4)]

for fun in functions:
    fun()

In your first example, I'm assuming that fl() is a typo, and you meant f() (because otherwise you'll be calling a list object, which isn't callable).

You know that func1(1) is calling the function and the result of this call is returned, so that in res = func1(1) the variable res will be the result of executing the function.. So, that list [func1(1), func1(2), ...] is a list of what this function returns. The function returns None, which isn't callable, that's why your code failed.

You want to call the function (not the result of calling the function!) with different arguments, and that's exactly what functools.partial is there for.

Upvotes: 1

cwallenpoole
cwallenpoole

Reputation: 81988

First, you're calling fl() which is trying to call the list as a function. that doesn't work.

In Python, putting () after a function evaluates the function and provides the return value. This means fl = [func1(1),func1(2),func1(3)] means "Create a list, and put the result of calling func1(1), func1(2), and func1(3)"

If you want to call the function later, then you can put the parameter into the list and walk through the list, or you can bind.

f = func1 # storing the function as a variable
fl = [1,2,3]

for v in fl: 
    f(v)

then you can do something like use lambda to bind:

f = func1 # storing the function as a variable
fl = [lambda :f(1), lambda :f(2), lambda :f(3)]

for v in fl: 
    v() # v is bound to the parameters, so you don't need to use a param

Upvotes: 1

user5777975
user5777975

Reputation:

From the code:

for f in f1:
    f1()

Explanation:

As you defined f1 as of type list and you are using that variable as function call. But python expects the function name should be a string type. So got the error list() type is not callable

But when you changed code to :

for f in f1:
    f()

here the f is of type string so python validated the type and so it didn't throw error

Upvotes: 1

Related Questions