Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting list to *args when calling function [duplicate]

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.

like image 768
andreas-h Avatar asked Oct 14 '22 00:10

andreas-h


People also ask

Can I pass list to* args?

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

How do you pass lists to args in Python?

Expand the dictionary with ** While specifying a dictionary with ** as an argument, the key will be extended as an argument name and value as the argument's value. Each and every single element will pass as the keyword arguments. Let's learn more about lists as arguments.


3 Answers

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.

like image 262
Bryan Oakley Avatar answered Oct 18 '22 18:10

Bryan Oakley


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],)
>>> 
like image 25
Ant Avatar answered Oct 18 '22 20:10

Ant


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

like image 3
intuited Avatar answered Oct 18 '22 20:10

intuited