Stop 04 · FunctionsTopics · 4/8

*args and **kwargs

Part of the Python Roadmap

In short

print() accepts any number of values, and many library functions accept any number of options. *args and **kwargs are how you write functions with that same flexibility, and how you unpack lists and dicts into a call.

*args collects any number of extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. The same * and ** symbols also unpack lists and dicts when calling a function.

The jaadu stuffs an overflowing cloth jhola with vegetables in one hand while balancing an open steel tiffin with separate compartments in the other.

Think of it like this

A jhola and a labelled tiffin

*args is a cloth jhola: throw in as many vegetables as you like, in any order, and they all go into one bag. **kwargs is a tiffin box with labelled compartments: "dal" here, "rice" there, "pickle" in the small one. One collects unnamed extras, the other collects named extras.

Watch it happen

register("Farhan", "BCA", "Python", city="Lucknow", year=2)

The call
name = "Farhan"
*args (tuple)
"BCA"
"Python"
**kwargs (dict)
city: "Lucknow"
year: 2

1/4The function is def register(name, *args, **kwargs). Python sorts the arguments into slots.

The big ideas

What you need to know

*args packs positionals

def total(*amounts) collects every extra positional argument into a tuple. The name args is only a convention; the * does the work.

**kwargs packs keywords

def profile(**details) collects extra keyword arguments into a dict of name to value.

The same symbols unpack

total(*prices) spreads a list into separate arguments, and profile(**info) spreads a dict into keyword arguments.

Parameter order

Regular, then *args, then keyword-only, then **kwargs: def f(a, b=1, *args, flag=False, **kwargs).

See it in code

Walk through the code

python
1def total_bill(*amounts):2    print(type(amounts), amounts)3    return sum(amounts)4 5 6def make_profile(name, **details):7    print(f"Name: {name}")8    for key, value in details.items():9        print(f"  {key}: {value}")10 11 12print(total_bill(120, 80, 45))   # <class 'tuple'> (120, 80, 45), then 24513make_profile("Farhan", city="Lucknow", course="BCA", year=2)14 15prices = [99, 149, 249]16print(total_bill(*prices))       # the list is unpacked: 49717 18info = {"city": "Kochi", "course": "B.Tech"}19make_profile("Anjali", **info)   # the dict is unpacked into keywords

1/5*amounts gathers all positional arguments into one tuple, which sum() can add up.

Packing in the def line, unpacking in the call. Same symbols, opposite directions.

Save yourself the pain

Common mistakes

Oops

Passing a list without * and getting one argument that is a whole list: total_bill(prices).

Do this instead

Write total_bill(*prices) to spread the items out as separate arguments.

Oops

Using **kwargs everywhere so callers can't tell which options exist.

Do this instead

Prefer named parameters with defaults. Reach for **kwargs when you truly accept open-ended options or pass them on to another function.

Oops

Putting **kwargs before *args in the def line.

Do this instead

The order is fixed: regular parameters, *args, keyword-only parameters, then **kwargs last.

Your mission

Flexible helpers

~25 min

Quick check

Inside def f(*args):, what is the type of args when you call f(1, 2, 3)?

Go deeper

  1. 1Write a total(*amounts) function that adds any number of prices.
  2. 2Write a function that prints every key=value pair passed as **kwargs.
  3. 3Pass a list into a function with *my_list and a dict with **my_dict.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge