liveBook · Manning

Variadic arguments

As explained in Python Workout, Second Edition

A variadic positional parameter collects an arbitrary number of positional arguments into a tuple.

Use a variadic positional parameter when a function should accept an unknown number of positional values. Python writes this parameter as *args; inside the function, args is a tuple. section 7.0 section 11.23

Reimplementing sum

A focused exercise is to write mysum(1, 2, 3) and mysum(10, 20, 30, 40, 50), adding the values without calling the built-in sum. Iterate over args rather than indexing it: the parameter is intended for an unknown number of values. section 2.6 section 7.3

Choose parameter types according to the function’s intended call pattern:

  • Use *args when callers may provide any number of positional values and the implementation will process them as a sequence, commonly with a for loop. section 7.3
  • Use a default parameter when a particular argument is optional and has a natural fallback, such as content=''. section 7.3
  • Use **kwargs for arbitrary name=value arguments; Python collects them separately in a dictionary rather than the positional tuple. section 7.0 section 7.3

How Python Workout, Second Edition covers it

How deep it goes
Defines tuple collection and iteration, then contrasts variadic parameters with defaults and keyword arguments; it stops short of deeper call mechanics.
Examples
Uses a custom summation function, optional XML content, keyword-generated XML attributes, and a generator that chains iterables.
What it assumes
Assumes familiarity with Python functions and iteration while reinforcing parameter design and tuple handling.
What you can do after
Build it from scratch by collecting positional inputs, iterating over them, and selecting defaults or keyword arguments when the call pattern requires them.
How it connects
Connects variadic arguments with flexible parameters, default values, keyword arguments, tuples, generators, and the iterator protocol.

Also explained in

Compare how 8 books explain variadic arguments →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.