🧩 Functions, lesson 4 of 6
*args and **kwargs
Accept any number of arguments, and spread lists and dicts into calls.
9 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
Some functions take any number of arguments, like
print. You can write your own:
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dict.
The names are only a convention; the stars do the work.
Average of anything
Add print(nums) inside the function to see the tuple.
Profile card with **kwargs
Add hobby="chess" to Ben's call.
What does this print?
The stars also work the other way, when calling:
f(*items) spreads a list into positional
arguments, and f(**options) spreads a dict into
keyword arguments.
Spread into a call
Compare print(nums) with print(*nums).
What does this print?
Checkout with a discount
Rewrite checkout so it accepts any number of
prices (*prices) plus a keyword-only
discount percent (default 0). Return the total
after the discount, rounded to 2 decimals.
checkout(10, 20) → 30 and
checkout(10, 20, discount=50) → 15.0.