Converting list to *args when calling function

145,839

Solution 1

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.

Solution 2

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],)
>>> 

Solution 3

*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.

Share:
145,839

Related videos on Youtube

andreas-h
Author by

andreas-h

Updated on February 01, 2020

Comments

  • andreas-h
    andreas-h over 4 years

    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.

  • user1066101
    user1066101 over 13 years
  • Russell Smith
    Russell Smith over 13 years
    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.
  • intuited
    intuited over 13 years
    @Bryan Oakley: The docs I linked to explain how to do that.
  • Russell Smith
    Russell Smith over 13 years
    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.
  • Matthias
    Matthias about 7 years
    Could you provide a qualitative citation for the "generally of the same type" part?
  • puzzledbeginner
    puzzledbeginner about 3 years
    lifesaver! i spent longer than I am going to admit trying to make a similar thing work! thanks ;-)