Python tip 18: arbitrary number of arguments
The print()
function can accept zero or more values separated by a comma. Here's how the function arguments are shown in help(print)
:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Here are some examples with varying number of arguments passed to the print()
function:
>>> print()
>>> print('hello')
hello
>>> print(42, 22/7, -100)
42 3.142857142857143 -100
You can write your own functions to accept arbitrary number of arguments as well. The packing syntax is similar to sequence unpacking. A *
prefix to an argument name will allow it to accept zero or more values. Such an argument will be packed as a tuple
data type and it should always be specified after positional arguments (if any). args
is often used as the variable name for this purpose. Here's an example:
>>> def many(x, *args):
... print(f'{x = }; {args = }')
...
>>> many()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: many() missing 1 required positional argument: 'x'
>>> many(1)
x = 1; args = ()
>>> many(1, 'two', 3)
x = 1; args = ('two', 3)
Here's a more practical example:
>>> def sum_nums(*args):
... total = 0
... for n in args:
... total += n
... return total
...
>>> sum_nums()
0
>>> sum_nums(3, -8)
-5
>>> sum_nums(1, 2, 3, 4, 5)
15
>>> sum_nums(*range(1, 6))
15
Use **
prefix to accept arbitrary number of keyword arguments. See also docs.python: Arbitrary Argument Lists.
Video demo:
See also my 100 Page Python Intro ebook.