2

I have a function:

def func(a,b,c,d,e,f,g):
    do something using the paramters

I would like to run the function func by taking param1 and param2 and so on in a loop.

I have the parameters inside a list, like:

param1 = list[a,b,c,d,e,f,g]
param2 = list[a1,b1,c1,d1,e1,f1,g1]

I tried

main_list = [param1,param2,....,param8]

for a in main_list:
    func(a)

But that doesn't seem to work!

EDIT:

My functions takes in 7 parameters, and I have to loop it 8 times, I have 8 such different parameter lists –

4
  • func(*a) instead of func(a). Commented Jul 17, 2015 at 10:08
  • Are you actually passing a lists of lists? Commented Jul 17, 2015 at 10:11
  • @PadraicCunningham: My functions takes in 7 parameters, and I have to loop it 8 times, I have 8 such different parameter lists Commented Jul 17, 2015 at 10:13
  • Just unpack in a loop then as suggested, change to func(*a) Commented Jul 17, 2015 at 10:15

4 Answers 4

2

Is this what you want:

def func(*vargs):
    for a in vargs:
       print a


func(*[1,2,3])
1
2

i.e.)

def func(*vargs):
    for a in vargs:
       print a


func(*main_list)

Edit

a,g,e=10,40,50

def func(a,b,c):
   print a,b,c


func(*[a,g,e])
10 40 50

3
Sign up to request clarification or add additional context in comments.

1 Comment

I would like to run my function, which takes in 7 parameters, all of which I have stored in a list
2

This is exactly what you asked for:

def func(a,b,c,d,e,f,g):
    pass

param1 = [1,2,3,4,5,6,7]
param2 = [11,21,31,41,51,61,71]

main_list = [param1, param2]

for a in main_list:
    func(*a)

Comments

2

Use the *args syntax:

for params in [param1, param2, param3, ...]:
    func(*params)

The *params syntax then expands the sequence into separate arguments for the function. Make sure that that number of positional arguments matches what your function expects, of course.

Demo:

>>> def func(a, b, c, d, e, f, g):
...     print a, b, c, d, e, f, g
... 
>>> param1 = ('a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1')
>>> param2 = ('a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2')
>>> for params in [param1, param2]:
...     func(*params)
... 
a1 b1 c1 d1 e1 f1 g1
a2 b2 c2 d2 e2 f2 g2

4 Comments

Do I also need to change my func to take only one argument? Because now I get the TypeError: func() takes exactly 7 arguments (8 given)
@ThePredator: your function does only take 7 parameters. Why are you trying to make it work with 8?
My functions takes in 7 parameters, and I have to loop it 8 times, I have 8 such different parameter lists
@ThePredator: ah, I misunderstood your setup; I thought param1 contained all values for the a argument, not the 7 arguments for that call.
0

Try to call the functions by unpacking the list of parameters in the arguments. Example -

main_list = [param1,param2,....,param8]

for a in main_list:
    func(*a)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.