168

In Python, how do I convert a list to *args?

I need to know because the function

scikits.timeseries.lib.reportlib.Report.__init__(*args)

wants several time_series objects passed as *args, whereas I have a list of timeseries objects.

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
andreas-h
  • 10,059
  • 17
  • 56
  • 72

3 Answers3

256

You can use the * operator before an iterable to expand it within the function call. For example:

timeseries_list = [timeseries1 timeseries2 ...]
r = scikits.timeseries.lib.reportlib.Report(*timeseries_list)

(notice the * before timeseries_list)

From the python documentation:

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

This is also covered in the python tutorial, in a section titled Unpacking argument lists, where it also shows how to do a similar thing with dictionaries for keyword arguments with the ** operator.

Bryan Oakley
  • 341,422
  • 46
  • 489
  • 636
22

yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.

so:

>>> def printer(*args):
 print args


>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>> 
Ant
  • 4,886
  • 2
  • 23
  • 42
2

*args just means that the function takes a number of arguments, generally of the same type.

Check out this section in the Python tutorial for more info.

intuited
  • 21,996
  • 7
  • 62
  • 87
  • 1
    I think the OP already knows this. The function takes multiple args but they have a single list they want to pass in as multiple args. – Bryan Oakley Oct 15 '10 at 12:37
  • @Bryan Oakley: The docs I linked to explain how to do that. – intuited Oct 15 '10 at 12:52
  • 6
    while that's true, the way you worded your answer it sounds like the link points to somewhere else. I think your answer will be more useful if you reword it to address unpacking rather than what *args means. – Bryan Oakley Oct 15 '10 at 13:56
  • Could you provide a qualitative citation for the "generally of the same type" part? – Matthias Apr 15 '17 at 18:01