I know you can use *args
in Python to allow a tuple or arguments. But how could one have two of these. Like *args
and *args1
?
Is this possible?
I know you can use *args
in Python to allow a tuple or arguments. But how could one have two of these. Like *args
and *args1
?
Is this possible?
I assume you mean in terms of function arguments, then no it isn't possible. The reason why is a tuple *args
can be of any length of 0 or more arguments. If you had another one, *args2
, how would you determined which arguments belong to *args
and which to *args2
? You can however include a **kwargs
which is a dictionary object of keyword arguments. For example:
def my_function(x, *args):
...
You can figure out what the args of *args
are. However, in
def my_function2(x, *args, *args):
...
You cannot determine which arguments go into args1
and which go into *args2
. However, for
def my_function3(x, *args, **kwargs):
...
It's possible to differentiate the arguments that belong to *args
and those that belong to **kwargs
because the arguments that belong to the **kwargs
take the form of arg = val
.
You can't have multiple variadic parameters of the same type in a function definition (e.g. def func(*args, *args1)
, but, in Python 3.5, you can pass arguments in that form when calling a function.
Python 3.4:
>>> print(*range(3), *range(3))
File "<stdin>", line 1
print(*range(3), *range(3))
^
SyntaxError: invalid syntax
Python 3.5:
>>> print(*range(3), *range(3))
0 1 2 0 1 2
It is not possible to pass *args
twice when calling a function (up until in Python 3.5)
>>> fun(*a, *b)
File "<stdin>", line 1
fun(*a, *b)
^
SyntaxError: invalid syntax
However, what you can do is concatenate two args
(list
or tuple
) as you pass them using +
. For example:
>>> def fun(*args):
... print(args)
...
>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9]
>>>
>>> fun(*a)
(1, 2, 3, 4, 5)
>>> fun(*b)
(6, 7, 8, 9)
>>> fun(*a+b)
(1, 2, 3, 4, 5, 6, 7, 8, 9)
The function definition can only have a single *args
definition, and all passed position arguments will end up in the args
variable in the order they were passed.