To complement @midlindnerâs examples, we have, as would be expected, variants, and also as expected, inherent provisos. The last can be demonstrated thus,
def mult_x_add_y(n, x = 1, y = 0):
return n * x + y
When we multiply by zero we get zero, hence we have a default value of 1 to permit the multiplication, albeit there is no change. By the same token we add zero, again so there is no change. The return value is an identity of the primary argument, n
when the defaults are in effect.
>>> def foo(*args):
print (type(args))
>>> foo(1,2,3,4,5,6,7,8,9,0)
<class 'tuple'>
>>>
Above we see that any length argument sequence is cast as a tuple.
>>> def foo(*args):
print (args)
>>> foo(1,2,3,4,5,6,7,8,9,0)
(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
>>>
Though it mightnât be so advisable to venture away from the uniform dynamics of the varying inputs, with careful design we can glean out the singular variables we want from the front of the list and lump the rest into another tuple.
>>> def foo(*args):
a = args[0] or None
b = args[1] or None
c = args[2] or None
d = args[3:]
print(a,b,c,d)
>>> foo(1,2,3,4,5,6,7,8,9,0)
1 2 3 (4, 5, 6, 7, 8, 9, 0)
>>>
But we need to go backâŚ
>>> def foo(*args):
print (args)
>>> foo()
()
>>> foo(10)
(10,)
>>>
Nothing in, and a tuple is still returned. A single argument and a tuple is returned with a comma after the value. Why? (10)
is not a tuple; (10,)
, is.
>>> foo(10,0)
(10, 0)
No more added comma. The above is unquestionably a tuple.
>>> foo(10,0, 0)
(10, 0, 0)
>>> foo(10,0, 0, 0)
(10, 0, 0, 0)
>>> foo(10,0, 0, 0, 0)
(10, 0, 0, 0, 0)
>>>
Back to the above,
>>> def foo(*args):
a = args[0] or 0
b = args[1] or 1
c = args[2] or 0
d = args[3:]
print(a, b, c, d)
>>> foo(0,0,0,0,0,0,0,0,0,0)
0 1 0 (0, 0, 0, 0, 0, 0, 0)
>>>
Change the variable names of a, b, and c, and we can return just the result we want, or the result and the residual data if we have some further use of it. Recall that it was mentioned that careful design would be involved.
>>> def foo(*args):
n = args[0] or 0
x = args[1] or 1
y = args[2] or 0
d = args[3:]
print(n,x,y,d)
return n * x + y
>>> foo(0,0,0,0,0,0,0,0,0,0)
0 1 0 (0, 0, 0, 0, 0, 0, 0)
0
>>>
>>> foo(10)
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
foo(10)
File "<pyshell#45>", line 3, in foo
x = args[1] or 1
IndexError: tuple index out of range
>>>
>>> foo(10, 0)
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
foo(10, 0)
File "<pyshell#45>", line 4, in foo
y = args[2] or 0
IndexError: tuple index out of range
>>>
>>> foo(10,)
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
foo(10,)
File "<pyshell#45>", line 3, in foo
x = args[1] or 1
IndexError: tuple index out of range
>>>
>>> foo(10,0,0,0)
10 1 0 (0,)
10
>>> foo(10, 5, 5)
10 5 5 ()
55
>>> foo(7, 5, 7)
7 5 7 ()
42
>>>
Mull this over. It bears discussion at some point. If now is not the time, then it should be some time soon.