Fix Python – Converting list to *args when calling function [duplicate]

Question

Asked By – andreas-h

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.

Now we will see solution for issue: Converting list to *args when calling function [duplicate]


Answer

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.

This question is answered By – Bryan Oakley

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0