Reputation: 4487
I'm invoking a third-party function with the head like def foo(*args)
, so that ordinarily I can use it in this way foo(a,b,c)
.
But now I have a list, say li = [a,b,c]
. I don't know how many elements it has until runtime. How to transfer all the elements of the list into the function foo
as parameters.
I've tried foo(li)
and foo(tuple(li))
, but they don't work. Please help.
Thank you.
Upvotes: 0
Views: 105
Reputation: 250961
use *
while calling the function, *
is used for unpacking a sequence into separate positional arguments during function call:
foo(*li)
demo:
>>> def foo(*args): print (args)
>>> foo(*range(10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Upvotes: 2
Reputation: 1670
Try passing li
with an *
before it as in foo(*li)
:
li = [1, 2, 3, 4, 5]
foo(*li)
For example:
>>> def f(*args):
... print args
...
>>> li = [1,2,3]
>>> f(*li)
(1, 2, 3)
Upvotes: 2