Python Function Arguments: Defaults, *args and **kwargs
Python gives you several ways to pass arguments, and knowing them makes functions both easier to call and easier to read at the call site. This chapter builds on the previous one.
Default values
A parameter written as exponent=2 has a default: if the caller leaves it out, Python uses 2. Parameters with defaults must come after those without. Defaults turn the common case into a short call, power(5), while keeping the general case available, power(2, 5).
Keyword arguments
Any argument can be passed by name: power(exponent=3, base=2). Named arguments may appear in any order and make calls self-documenting, especially for booleans: save(data, overwrite=True) is clearer than save(data, True). Positional arguments must come before keyword arguments in a call.
Collecting extra arguments
- A parameter written
*numberscollects any extra positional arguments into a tuple. That is howtotal(1, 2, 3)accepts any count. - A parameter written
**detailscollects extra keyword arguments into a dictionary.
The names args and kwargs are only conventions; the stars are what matter. The same stars work in reverse at a call: power(*pair) spreads a sequence into positional arguments and f(**options) spreads a dict into keyword arguments.
Expected output
25
32
8
<class 'tuple'> (1, 2, 3)
6
Emma {'city': 'Austin', 'joined': 2025}
['pen'] ['ink']The mutable default trap
Default values are evaluated once, when the def statement runs, not on every call. If the default is a mutable object such as a list, every call that relies on it shares the same list, and items pile up between calls. The fix, shown in add_item, is to use None as the default and create a fresh list inside the function. The output shows each call getting its own list.
Common mistakes
- Using
[]or{}as a default value. - Putting a parameter without a default after one with a default, which is a
SyntaxError. - Passing the same argument twice, once by position and once by name, which raises
TypeError.
Summary
param=valuesets a default used when the caller omits the argument.- Keyword arguments make calls explicit and order-independent.
*argsgathers extra positional arguments in a tuple;**kwargsgathers extra keyword arguments in a dict.- Use
Noneinstead of a mutable default.
Quiz: Default and keyword arguments