*args and **kwargs

Functions, lesson 4 of 6

🧩 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:

  • *args collects extra positional arguments into a tuple.
  • **kwargs collects extra keyword arguments into a dict.

The names are only a convention; the stars do the work.

Example

Average of anything

Add print(nums) inside the function to see the tuple.

Example

Profile card with **kwargs

Add hobby="chess" to Ben's call.

Quiz

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.

Example

Spread into a call

Compare print(nums) with print(*nums).

Quiz

What does this print?

Exercise

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.