PY-101 ยท Functions
*args and **kwargs
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
*args collects any number of extra positional arguments into a tuple, and **kwargs collects any number of keyword arguments into a dictionary. They let one function accept as many inputs as the caller wants. The names args and kwargs are a convention; the * and ** do the work.
- Collect extra arguments with *args
- Collect named options with **kwargs
- Loop over them
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
def total(*prices):print("Got", len(prices), "prices")return sum(prices)def profile(**info):for key, value in info.items():print(key, "=", value)print(total(120, 80, 45))profile(name="Asha", city="Pune")
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
Got 3 prices
245
name = Asha
city = Pune ๐ฏ Write average(*nums) that returns the average of any number of values. average(2, 4, 6) should be 4.0.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
return sum(nums) / len(nums)
- The problemA shopping cart total should work for 2 items or 20. You cannot write a parameter for each one, so the function takes "as many as you give me".
- The Python idea
def f(*args, **kwargs):*args collects any number of extra positional arguments into a tuple, and **kwargs collects any number of keyword arguments into a dictionary. - In real lifePython's own print(*objects, sep=" ", end="\n") uses *objects so you can print any number of values.
Start with a question
A shopping cart total should work for 2 items or 20. You cannot write a parameter for each one, so the function takes "as many as you give me".
Logging, formatting and framework code all accept flexible arguments. Reading library code needs this.
Explain it like I'm 10
*args is a bag that holds however many toys you put in. **kwargs is a bag of labelled boxes.
The technical explanation
def total(*prices): makes prices a tuple of everything passed in.
def profile(**info): makes info a dict: profile(name="Asha", city="Pune") gives {"name": "Asha", "city": "Pune"}.
You can loop over them like any tuple or dict.
Syntax
def f(*args, **kwargs):
... Real-world scenario
Python's own print(*objects, sep=" ", end="\n") uses *objects so you can print any number of values.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Scope โQuestions people ask
What does * mean before a parameter in Python?
It collects any extra positional arguments into a tuple. In a call, *list does the opposite: it spreads a list into separate arguments.
When should I use **kwargs?
When a function passes options through to another function, or accepts settings whose names you cannot list in advance.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What does * mean before a parameter in Python?
It collects any extra positional arguments into a tuple. In a call, *list does the opposite: it spreads a list into separate arguments.
beginner When should I use **kwargs?
When a function passes options through to another function, or accepts settings whose names you cannot list in advance.
intermediate What type is args in def f(*args)?
tuple. *args collects a tuple.
intermediate What type is kwargs in def f(**kwargs)?
dict. **kwargs collects a dict.
Quick revision
Remember
- Collect extra arguments with *args
- Collect named options with **kwargs
- Loop over them
- Order in a definition: normal parameters, then *args, then keyword-only ones, then **kwargs.
Syntax
def f(*args, **kwargs):
... Official documentation
- Arbitrary argument lists (docs.python.org)