1

I have a list with x number of parameters

[p1,p2,p3...pk]

and I need each item on the list to pass as a parameter so it goes like

function(p1,p2..,pk)

How can I do this without changing the function to recieve a list? something like iter items, but I cant just go next(list) on each parameter because I don't know how much parameters i'm going to insert into the function

gramsch
  • 379
  • 1
  • 5
  • 18

2 Answers2

4

Use * operator

list = [1, 2, 3, n]
foo(*list) # Function with n arguments

For example:

def foo(one, two):
    print(one, two)


list_1 = [1, 2]
list_2 = [1, ]

# Call with list_* variable
foo(*list_1) # Print 1, 2
foo(*list_2) # TypeError, but requiere more arguments.

For solve TypeError, can use *args for has dynamic arguments in your function

  • After looking at your answer, I realise that the question might be interpreted in two ways - a) how to call it given a list, and b) how to make the function to recieve :D – Jmons May 05 '17 at 09:20
  • 1
    The question was about calling a function given a list, I didn't realize the `*` simbol could be also when calling a function, that was the point of my question – gramsch May 05 '17 at 10:55
0

Python can take arguments as *args:

def foo(*args):
    print len(args)
    for x in args:
        print (x)

foo("a")
foo("a","b","c")

You can mix and match args and *args as well if you have a leading argument you need - something like def foo(x,y, *args):

Jmons
  • 1,766
  • 17
  • 28