Writing a parameter with an equals sign and a value in a function definition makes that parameter optional — if the caller omits it, the function uses the given default instead. Default values are evaluated exactly once, at the moment the function is defined, not on every call, which is why using a mutable object like a list or dict as a default is a classic bug: that same object is shared and can accumulate state across calls that don't override it.
1Understanding Default Parameter Value
Writing a parameter with an equals sign and a value in a function definition makes that parameter optional — if the caller omits it, the function uses the given default instead. Default values are evaluated exactly once, at the moment the function is defined, not on every call, which is why using a mutable object like a list or dict as a default is a classic bug: that same object is shared and can accumulate state across calls that don't override it.
Never use a mutable object, like an empty list or dict, as a default parameter value — use None as the default instead, and create a fresh mutable object inside the function body when it's actually needed.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice"))
print(greet("Bob", "Hi"))2Practical Example
Here is a real-world application of Default Parameter Value showing how it is used in production Python code.
def add_item(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add_item("a"))
print(add_item("b"))3Best Practices
Follow these guidelines when working with Default Parameter Value:
1. Use None as the default for optional mutable arguments, creating the real object inside the function body
2. Put parameters with defaults after all parameters without defaults, since Python's syntax requires that order
3. Choose defaults that represent a sensible, safe fallback, not just an arbitrary placeholder value
Tip: Never use a mutable object, like an empty list or dict, as a default parameter value — use None as the default instead, and create a fresh mutable object inside the function body when it's actually needed.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice"))
print(greet("Bob", "Hi"))