Python Default Arguments
In this page:
def function_name(parameter, optional=default_value):
# body
return value
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"): # name defaults to "friend" if the caller omits it
print("Hello,", name)
greet() # uses the default value
greet("Alex") # overrides the default
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"): # required parameter must come before the defaulted one
print(greeting, name)
greet("Hi") # name falls back to its default
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): # None avoids sharing one list across every call
if cart is None:
cart = [] # a fresh list is created for this call
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") # item is positional, note is keyword, qty uses its default
- Using a mutable default like
def add(item, items=[]), which is shared between calls; useNoneand create the list inside. - Putting a non-default parameter after a default one, as in
def f(a=1, b), which is aSyntaxError. - Expecting a default like
time=datetime.now()to refresh each call; it is evaluated once at definition time.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: