Python ยท Chapter 21 of 45

*args and **kwargs

`*args` collects extra POSITIONAL arguments into a tuple. `**kwargs` collects extra KEYWORD arguments into a dict.

Use them when a function needs to accept a flexible number of arguments.

*args

The star unpacks/packs positional arguments. Inside the function `args` is a tuple.

**kwargs

Two stars unpack/pack keyword arguments. Inside the function `kwargs` is a dict.

Example 1 (python)
def total(*nums):
    return sum(nums)

print(total(1, 2, 3, 4))
Output
10

*nums packs all positional args into a tuple.

Example 2 (python)
def profile(**info):
    for k, v in info.items():
        print(k, "=", v)

profile(name="Ana", age=25)
Output
name = Ana
age = 25

**info collects keyword args into a dict.

Key points

  • *args -> tuple of extra positional args.
  • **kwargs -> dict of extra keyword args.
  • Names `args`/`kwargs` are convention, not required.
  • Order: normal, *args, **kwargs.
๐Ÿ’ก Note: You can also USE `*` and `**` to UNPACK an iterable/dict into function arguments: `f(*mylist)`, `f(**mydict)`.

๐Ÿ“ Quick Quiz

1. *args collects arguments into a:

2. **kwargs collects arguments into a:

3. Which order is correct in a function signature?