← Python lessons

Python Default Arguments and Keyword Arguments

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A default argument is the value a parameter uses when the caller leaves it out. A keyword argument passes a value by parameter name, not position.

Read Parameters & Return first.

This lesson covers one thing: making parameters optional and naming them in a call. Every block below runs on its own and prints the result shown under it.

Give a parameter a default value

Write name=value in the def line. The caller may now skip that argument.

def greet(name, greeting="Hello"):
    print(greeting + ",", name)

greet("Ada")
greet("Bo", "Hi")

This prints Hello, Ada then Hi, Bo. The second call replaces the default.

Pass arguments by name

A keyword argument says which parameter it fills, so the order no longer matters.

def greet(name, greeting="Hello"):
    print(greeting + ",", name)

greet(greeting="Welcome", name="Cy")
greet("Di", greeting="Hey")

This prints Welcome, Cy then Hey, Di. Use keywords when a call would otherwise be hard to read, such as resize(4, 3, True) versus resize(4, 3, keep_shape=True).

Order rules for defaults and keywords

Parameters with defaults must come after those without. In a call, positional arguments must come before keyword ones. Both mistakes stop the program before it runs:

def greet(greeting="Hello", name):    # SyntaxError: non-default after default
    print(greeting + ",", name)

greet(name="Ada", "Hi")               # SyntaxError: positional after keyword

Passing the same parameter twice, as in greet("Ada", name="Bo"), raises TypeError when the call runs.

Avoid a list as a default value

A default is made once, when def runs, not on every call. A list default is shared by every call that uses it.

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

print(add_item("pen"))
print(add_item("cup"))

This prints ['pen'] then ['pen', 'cup']. The second call reused the first call's list. Use None as the default and make a new list inside:

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

print(add_item("pen"))
print(add_item("cup"))

Now each call prints a list with one item. Numbers, strings, True/False and None are safe defaults because they cannot change.

Note: This lesson leaves out *args, **kwargs and keyword-only parameters (def f(a, *, b)). They follow the same idea of matching arguments to parameters.

See also: Defining Functions.

Your turn

Complete make_label so size defaults to 10 and unit defaults to "cm". It returns text like Box: 10cm. The three calls use the defaults, a positional size and a keyword unit.

# add the def line with two default values, and the return line
print(make_label("Box"))
print(make_label("Tube", 25))
print(make_label("Rope", unit="m"))

Expected output

Box: 10cm
Tube: 25cm
Rope: 10m