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 –

Srivatsan
  • 9,225
  • 13
  • 58
  • 83

4 Answers4

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 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)` – Srivatsan Jul 17 '15 at 10:10
  • 1
    @ThePredator: your function does only take 7 parameters. Why are you trying to make it work with 8? – Martijn Pieters Jul 17 '15 at 10:10
  • My functions takes in 7 parameters, and I have to loop it 8 times, I have 8 such different parameter lists – Srivatsan Jul 17 '15 at 10:12
  • 1
    @ThePredator: ah, I misunderstood your setup; I thought `param1` contained all values for the `a` argument, not the 7 arguments for that call. – Martijn Pieters Jul 17 '15 at 10:12
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
The6thSense
  • 8,103
  • 8
  • 31
  • 65
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)
jimifiki
  • 5,377
  • 2
  • 34
  • 60
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)
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176