1.2.29 · D3Introduction to Programming (Python)

Worked examples — ` - args` and ` - kwargs` — flexible argument passing

2,302 words10 min readBack to topic

The scenario matrix

Think of every call to a flexible function as a point on a grid. One axis is how many positional values arrive; the other is how many keyword values arrive; and there are special "edge" columns for the weird cases. Below is that grid flattened into a checklist — every row is one distinct thing that can go wrong or surprise you.

Cell Scenario class Covered by
A *args catches many extra positionals Ex 1
B *args catches zero (empty tuple ()) — degenerate Ex 2
C **kwargs catches many keywords Ex 3
D Named param + *args + **kwargs all at once (the split) Ex 4
E Call-site unpacking: spread a list with *, a dict with ** Ex 5
F Collision: same key given twice → TypeError Ex 6
G Keyword-only parameters (the lone * separator) Ex 7
H Dict-merge with {**a, **b} — later key wins (override) Ex 8
I Real-world word problem: a shopping-cart total Ex 9
J Exam twist: forgetting * at the call site (single-arg trap) Ex 10

Every numeric or structural answer below is machine-checked in the verify block.

Figure — ` - args` and ` - kwargs` — flexible argument passing

Look at the figure above: the incoming values flow left to right. Named slots fill first (black), then the leftover positionals pour into the *args tuple (red), and any stray name=value pairs drop into the **kwargs dict. Keep this picture in mind for every example.


Cell A — many extra positionals


Cell B — zero extras (degenerate / empty)


Cell C — many keywords into a dict


Cell D — the three-way split


Cell E — call-site unpacking (the mirror direction)


Cell F — the collision error


Cell G — keyword-only parameters


Cell H — dict merge, later wins


Cell I — real-world word problem


Cell J — the exam twist


Recall One-line self-test for the whole matrix

Predict all ten answers, then check: 14, 0, the pairs list, (1,(2,3),{...}), 24 twice, TypeError, ("db",5432,30), the merged dict, 400.0, and (1, 3). A: 14 ::: sum of 2+3+4+5 B: total() ::: 0 — args is the empty tuple F: collision ::: TypeError — name got two values J: total(nums) vs total(*nums) ::: 1 then 3


Connections

  • Functions and Parameters — the fixed-slot baseline every example bends.
  • Default Arguments — powers discount=0, shipping=0, timeout=30 above.
  • Tuples — what *args builds (Ex 1, 2, 4, 10).
  • Dictionaries — what **kwargs builds and what {**a,**b} merges (Ex 3, 8).
  • Decorators — the forwarding pattern generalises Ex 4 and 5.
  • Unpacking Assignment — the same star idea, on the left of =.