Editor settings

General settings

Save settings

Learn to program with Python

Mutable objects as default arguments #

A few lessons ago, we created a function with default arguments. However, something strange happens when we use mutable objects, such as dicts or lists as default arguments.

Here's an example:

def add_key_to_dict(key, value, the_dict={}):
    the_dict[key] = value
    return the_dict

new_object = add_key_to_dict("year", 2050)
another_object = add_key_to_dict("color", "yellow")
print(new_object) # {'year': 2050, 'color': 'yellow'}
print(another_object) # {'year': 2050, 'color': 'yellow'}

We would expect new_object and another_object to be different objects, but they are the same object.

In Python functions, the default values are initialized only once when the function is defined. They are not created every time the function is called. Therefore, the_dict in the example above is the same object every time we call the function. And when we call the_dict[key] = value, we operate on the same dictionary.

To set a mutable object as a default argument, set the value to None and use the if statement to check if the value is None. Like so:

def add_key_to_dict(key, value, the_dict=None):
    if the_dict is None:
        the_dict = {}
    the_dict[key] = value
    return the_dict

new_object = add_key_to_dict("year", 2050)
another_object = add_key_to_dict("color", "yellow")
print(new_object) # {'year': 2050}
print(another_object) # {'color': 'yellow'}
Any value other than None will also work, but None is a common choice.

We can take a step further to avoid causing side effects altogether:

def add_key_to_dict(key, value, the_dict=None):
    if the_dict is None:
        result = {}
    else:
        result = the_dict.copy()
    result[key] = value
    return result

Exercise #

Update the default argument in the function add_list_item()

Tests #

  • add_list_item(3, [1, 2]) should return [1, 2, 3]
  • add_list_item(1) should return [1], and subsequent add_list_item(2) should return [2]
Output will be displayed here