How to expand a list to function arguments in Python
It exists, but it's hard to search for. I think most people call it the "splat" operator.
It's in the documentation as "Unpacking argument lists".
You'd use it like this for positional arguments:
values = [1, 2]
foo(*values)
There's also one for dictionaries to call with named arguments:
d = {'a': 1, 'b': 2}
def foo(a, b):
pass
foo(**d)
Pass a list to function with variable number of args in python
Yes, just unpack the list using the same *args
syntax you used when defining the function.
my_list = [1,2,3]
result = add(*my_list)
Also, be aware that args[1:]
contains strings. Convert these strings to numbers first with
numbers = [float(x) for x in args[1:]]
or
numbers = map(float, args[1:]) # lazy in Python 3
before calling add
with *numbers
.
Short version without your add
function:
result = sum(map(float, args[1:]))
Pythonic way to expand list elements as individual actual parameters to a function (like matlab)?
Put a * in front of the list name in the function call (look here for more info http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists).
So, if your list was L, you would do
result = f(*L)
If you only want to use certain elements of L, say from i to j (not including j since slicing is exclusive on the right side), then first slice the list, and then do the same as above:
result = f(*L[i:j])
For your last example of inputting an argument and using other list elements as other arguments, it's similar, see below:
lst = [1, 2, 3, 4]
def f(a, b, c, d):
return b
print(f(1, *lst[1: 4]))
#this would print 2
Converting list to *args when calling function
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.
Pass a list to a function to act as multiple arguments
function_that_needs_strings(*my_list) # works!
You can read all about it here.
Expanding tuples into arguments
myfun(*some_tuple)
does exactly what you request. The *
operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.
Call a function with argument list in python
To expand a little on the other answers:
In the line:
def wrapper(func, *args):
The * next to args
means "take the rest of the parameters given and put them in a list called args
".
In the line:
func(*args)
The * next to args
here means "take this list called args and 'unwrap' it into the rest of the parameters.
So you can do the following:
def wrapper1(func, *args): # with star
func(*args)
def wrapper2(func, args): # without star
func(*args)
def func2(x, y, z):
print x+y+z
wrapper1(func2, 1, 2, 3)
wrapper2(func2, [1, 2, 3])
In wrapper2
, the list is passed explicitly, but in both wrappers args
contains the list [1,2,3]
.
Using multiple arguments in multiple functions efficiently
Here is a method using classes as mentioned in the comments.
class test:
def __init__(self,voltage = 5, state = "bleedin", status = 0):
self.arguments = {'voltage' : voltage, 'state' : state, 'status': status}
#You essentially merge the two dictionary's with priority on kwargs
def printVars(self,**kwargs):
print({**self.arguments,**kwargs})
Here is a sample run
>>> a = test()
>>> a.printVars(status = 5, test = 3)
{'voltage': 5, 'state': 'bleedin', 'status': 5, 'test': 3}
Python Function Equivalent to * for Expanding Arguments?
You'll need to write your own recursive function that applies arguments to functions in nested tuples:
def recursive_apply(*args):
for e in args:
yield e[0](*recursive_apply(*e[1:])) if isinstance(e, tuple) else e
then use that in your function call:
next(recursive_apply(nestedFunction))
The next()
is required because recursive_apply()
is a generator; you can wrap the next(recursive_apply(...))
expression in a helper function to ease use; here I bundled the recursive function in the local namespace:
def apply(nested_structure):
def recursive_apply(*args):
for e in args:
yield e[0](*recursive_apply(*e[1:])) if isinstance(e, tuple) else e
return next(recursive_apply(nested_structure))
Demo:
>>> def fp(num):
... def f(*args):
... res = sum(args)
... print 'fp{}{} -> {}'.format(num, args, res)
... return res
... f.__name__ = 'fp{}'.format(num)
... return f
...
>>> for i in range(3):
... f = fp(i + 1)
... globals()[f.__name__] = f
...
>>> c1, c2, c3 = range(1, 4)
>>> nestedFunction = (fp1, c1, (fp2, c2, c3), (fp3,))
>>> apply(nestedFunction)
fp2(2, 3) -> 5
fp3() -> 0
fp1(1, 5, 0) -> 6
6
Related Topics
How to Check If a Python Module Exists Without Importing It
Finding Indices of Matches of One Array in Another Array
How to Create Test and Train Samples from One Dataframe with Pandas
Importing an Ipynb File from Another Ipynb File
Maximum Value for Long Integer
Replace() Method Not Working on Pandas Dataframe
Creating a New Column Based on If-Elif-Else Condition
Extracting Date from a String in Python
Pandas Select from Dataframe Using Startswith
List on Python Appending Always the Same Value
Pandas: Merge (Join) Two Data Frames on Multiple Columns
Setting Camera Parameters in Opencv/Python
Pandas Groupby, Then Sort Within Groups