Lesson 4 of 10
Sometimes you don't know how many arguments a function will get. print() is a good example —
it happily takes one argument or ten.
*args
Putting * before a parameter name collects all extra positional arguments into a tuple.
def total(*numbers):
result = 0
for n in numbers:
result += n
return result
print(total(1, 2))
print(total(1, 2, 3, 4, 5))
print(total())
Inside the function, numbers is an ordinary tuple — loop it, len() it, index it. With no
arguments it's simply empty.
The name args is only a convention; the * is what matters. *numbers is clearer here, and
you should name it for what it holds.
You can mix normal parameters with *args, as long as the starred one comes last:
def describe(label, *values):
print(f"{label}: {values}")
describe("Scores", 90, 85, 100)
**kwargs
Two stars collects extra keyword arguments into a dictionary.
def make_user(**details):
return details
print(make_user(name="Ada", role="admin"))
Inside, details is a normal dictionary — use .get(), .items(), everything from Module 3.
def show(**options):
for key, value in options.items():
print(f"{key} = {value}")
show(theme="dark", font="mono")
Combining everything
The full order is: normal parameters, then *args, then keyword parameters with defaults, then
**kwargs.
def report(title, *values, sep=", ", **meta):
print(title)
print(sep.join([str(v) for v in values]))
print(meta)
report("Scores", 90, 85, 100, sep=" | ", author="Ada")
You will rarely need all four at once, but this is the order Python requires.
Unpacking when calling
The stars work in the other direction too — spreading a list or dictionary into arguments:
def add(a, b, c):
return a + b + c
numbers = [1, 2, 3]
print(add(*numbers))
values = {"a": 1, "b": 2, "c": 3}
print(add(**values))
*numbers says "use each item as a separate positional argument." **values says "use each
key/value pair as a keyword argument."
Try it yourself
Write total(*numbers) that sums however many numbers it's given.
Checkpoint
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.- Order: normal,
*args, keyword-with-default,**kwargs. - At the call site,
*listand**dictunpack into arguments.
Questions about this lesson
Log in to ask a question.