Flexible Arguments: *args and **kwargs
Sometimes you do not know how many arguments will be passed. Python lets a parameter soak up any extra ones.
*args collects all extra positional arguments into a tuple:
def total(*args):
result = 0
for n in args:
result += n
return result
print(total(1, 2, 3)) # 6
print(total(10, 20)) # 30
print(total()) # 0Inside the function, args is just a tuple you can loop over. The * is what does the collecting; the name args is only a convention.
**kwargs collects all extra keyword arguments into a dictionary:
def describe(**kwargs):
parts = []
for key, value in kwargs.items():
parts.append(f"{key}={value}")
return ", ".join(parts)
print(describe(name="Sam", age=30)) # name=Sam, age=30You can combine fixed parameters with both. The order in the def is: normal parameters, then *args, then **kwargs:
def report(label, *args, **kwargs):
return (label, args, kwargs)
print(report("scores", 9, 8, mode="avg"))
# ('scores', (9, 8), {'mode': 'avg'})Define a function my_sum that uses *args to accept any number of numbers and returns their total. my_sum(1, 2, 3) returns 6, and my_sum() returns 0. You may use Python's built-in sum() on args, or write a loop.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.