Python Default Arguments
In this page:
What are Default Arguments?
A default argument supplies a fallback value used automatically when the caller omits that argument — written with = in the function definition, like def greet(name="friend"): — making that parameter effectively optional.
Example: What are Default Arguments?
def greet(name="friend"):
print("Hello,", name)
greet()
greet("Alex")
Rules for Default Arguments
Every default-valued parameter must come after all parameters without a default in the function's definition; putting a required parameter after an optional one raises a SyntaxError, since Python couldn't otherwise tell which arguments map to which parameter.
Example: Rules for Default Arguments
def greet(greeting, name="friend"):
print(greeting, name)
greet("Hi")
Mutable Default Arguments Warning
Using a mutable object like [] or {} as a default value is a classic Python trap: the default is created exactly once when the function is *defined*, not each time it's called, so every call that doesn't override it shares — and can silently mutate — the same list.
Example: Mutable Default Arguments Warning
def add_item(item, cart=[]):
cart.append(item)
return cart
print(add_item("apple"))
print(add_item("banana")) # shares the same list from the first call
Dynamic Default Values
The standard fix for that trap is defaulting the parameter to None and building the real default value inside the function body when needed — this guarantees a fresh object is created on every call instead of one being reused across calls.
Example: Dynamic Default Values
def add_item(item, cart=None):
if cart is None:
cart = []
cart.append(item)
return cart
print(add_item("apple"))
print(add_item("banana"))
Combining Positional, Keyword and Defaults
A single call can mix positional, keyword, and default arguments together, but positional arguments must always be listed first — Python resolves them left to right before matching any remaining keyword arguments to their parameters.
Example: Combining Positional, Keyword and Defaults
def order(item, qty=1, note="none"):
print(item, qty, note)
order("book", note="gift wrap")
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: