← Back to Python Course | Chapter 4: Functions | Lesson 4 of 9

Python Default Arguments

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?

python
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

python
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

python
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

python
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

python
def order(item, qty=1, note="none"):
    print(item, qty, note)

order("book", note="gift wrap")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.