IntermediateLesson firstCategory 11 of 20

Advanced Arguments

Use *args, **kwargs, and argument unpacking. Read the lesson first, then move through the exercises in order.

8 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Data Accumulator

Study Material

Read the full lesson

Why advanced arguments exist

Sometimes you want a function that accepts any number of inputs. Python gives you *args for extra positional arguments and **kwargs for extra keyword arguments.

Using *args

*args collects extra positional values into a tuple.

python
def total(*args): return sum(args) print(total(1, 2, 3))

Using **kwargs

**kwargs collects extra keyword values into a dictionary.

python
def build_profile(**kwargs): return kwargs print(build_profile(name="Lina", age=28))

Parameter order matters

The usual order is: normal parameters, *args, keyword-only parameters, then **kwargs.

python
def greet(greeting, *names, punctuation="!"): for name in names: print(greeting, name + punctuation)

Keyword-only parameters

You can force a parameter to be keyword only with a *.

python
def save(path, *, overwrite=False): print(path, overwrite) save("file.txt", overwrite=True)

Unpacking when calling

You can unpack a list or dict into function arguments.

python
nums = [1, 2, 3] print(total(*nums)) options = {"sep": "-", "end": "!"} print("a", "b", **options)

Common mistakes to avoid

  • Forgetting that *args is a tuple, not a list.
  • Passing the same argument twice (once positionally and once by name).
  • Putting **kwargs before *args in the function signature.

What you should understand after this lesson

  • When and why to use *args and **kwargs.
  • How to enforce keyword-only parameters.
  • How to unpack sequences and dictionaries when calling functions.

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.