PythonMastery
Python programs · Functions · beginner

Default arguments in Python

Give a function parameter a default value so callers can leave it out. Also shows the mutable default mistake and how to avoid it.

A default argument is a parameter with a value already filled in. If the caller does not pass that argument, Python uses the default.

The program

python
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Ada"))
print(greet("Linus", "Hi"))
print(greet("Grace", greeting="Good morning"))
output
Hello, Ada!
Hi, Linus!
Good morning, Grace!

How it works

The mutable default mistake

The default value is created once, when Python runs the def line. It is not created again on each call. With a list as the default, every call shares the same list:

python
def add_item(item, basket=[]):
    basket.append(item)
    return basket

print(add_item("apple"))
print(add_item("bread"))
output
['apple']
['apple', 'bread']

The second call still sees "apple" from the first call. Use None as the default and create a new list inside the function:

python
def add_item(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

print(add_item("apple"))
print(add_item("bread"))
output
['apple']
['bread']

Learn the idea: Functions & Scoping