Mutable default arguments

It's a common trap for Python newcomers, the mutable default arguments. Let's take an example of the function accumulating numbers in a list:

def add_numbers(new_number, numbers = []):
  numbers.append(new_number)
  return numbers

Now, when you run the following code snippet:

numbers1 = add_numbers(1)
numbers2 = add_numbers(2)

You may be expecting the following output:

numbers1 = [1]
numbers2 = [2]

However the default arguments in Python are evaluated only once, when the function is defined, and not at every call. Hence, the outcome will be:

numbers1 = [1]
numbers2 = [1, 2]

If you really need to initialize the arguments each time, you should do it lazily:

def add_numbers(new_number, numbers = None):
  if numbers is None:
    numbers = []
  numbers.append(new_number)
  return numbers