Default, Keyword, *args & **kwargs
Lesson 2 of 6 · View course roadmap
Learn the idea
Python's argument system is wonderfully flexible:
- Defaults:
def greet(name, punct="!")— callers may omitpunct - Keyword args:
greet(punct="?", name="Bo")— order-free, self-documenting *args: collects extra positional args into a tuple —def total(*nums)**kwargs: collects extra keyword args into a dict
Classic trap: never use a mutable default like def f(items=[]) — the list is created once and shared between calls. Use items=None and create inside.
Where you'll use this
Open any library's docs: requests.get(url, params=None, timeout=None, **kwargs) — defaults, keywords and kwargs everywhere. Understanding this lesson is understanding how every Python API is designed.
Common mistakes
- The mutable default trap:
def add(item, items=[])shares ONE list across all calls. It's the most famous Python gotcha — useitems=Nonethenitems = items or []. - Positional after keyword:
f(x=1, 2)is a SyntaxError — keywords go last. - Forgetting that *args is a tuple inside the function — you can loop it and len() it.
Pro tip
The * also unpacks at call time: print(*[1, 2, 3]) is print(1, 2, 3), and merge = {**d1, **d2} for dicts. Packing and unpacking are the same symbol in opposite directions.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +30 XP
Write describe(name, role="student") that returns "{name} is a {role}". Print describe("Ada") and describe("Grace", role="admiral").
Ada is a student Grace is a admiral
Use an f-string in the return.
def describe(name, role="student"):
return f"{name} is a {role}"
print(describe("Ada"))
print(describe("Grace", role="admiral"))
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.