Lesson 21 of 60
โฎPrev Nextโฏ

PY-101 ยท Functions

*args and **kwargs

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

21of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    *args and **kwargs, running
    1. def total(*prices):
    2. print("Got", len(prices), "prices")
    3. return sum(prices)
    4. def profile(**info):
    5. for key, value in info.items():
    6. print(key, "=", value)
    7. print(total(120, 80, 45))
    8. profile(name="Asha", city="Pune")
    Press โ–ถ to watch Python run this, one line at a time.
    1. 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".
    2. The Python ideadef 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.
    3. 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):
        ...

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Python's own print(*objects, sep=" ", end="\n") uses *objects so you can print any number of values.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What type is args in def f(*args)?
    2. 2. What type is kwargs in def f(**kwargs)?
    3. 3. def f(*a): return len(a). f(1, 2, 3)?
    4. 4. Are the names args and kwargs required?
    5. 5. def f(**k): return k["x"]. f(x=5)?

    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