We’ve already seen some functions that accept a variable number of arguments like
zip(). Yet, we haven’t created one ourselves. How to write a function that can handle a variable number of arguments?
When printing elements, we can call the
print()function with as many arguments as we want and it will print all of them:
print('Hi') # Hi print('Hi', 'how', 'are', 1) # Hi how are 1 print(1, 2, 3, 8) # 1 2 3 8
If we take a look at the function signature of
print()in the official python docs, the first argument actually captures the whole list of arguments (non-keyword) passed to it. The same holds for the zip function:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) zip(*iterables, strict=False)
We can define our own functions that accept a variable number of arguments with an asterisk
def income(*purchases): total = 0 for purchase in purchases: total += purchase return total print(income(1, 2, 3, 4, 10)) # 20
Here we can treat
purchasesas a list of numbers. We can access its length with
len(), we can loop over the elements with a
Implement a function
num_args()that would return the number of arguments passed to it.
Example calls to a function:
def num_args(*args): ... print(num_args(1, 2, 3)) # 3 print(num_args()) # 0 print(num_args('Anna')) # 1
Pro tip 😎: It’s also possible to turn a simple list into
a = [1, 2, 3, 'hello'] print(*a) # This is equivalent to print(1, 2, 3, 'hello')
Now you know how to easily print lists.