0

This:

def f(i,values = [99]):
    values.append(i)
    print (values)

f(1)
f(2)

has this result:

[99, 1]
[99, 1, 2]

Why isn't values (re)set to [99] every time I call the function? I would have thought it is the same as this:

def f(i):
    values = [99]
    values.append(i)
    print (values)

f(1)
f(2)
Moss
  • 325
  • 2
  • 16

1 Answers1

0

Because lists are mutable.

The arguments you pass to function binds to the object, Objects can be mutable (like lists) or immutable (like integers, strings in Python).

Unlike immutable types (e.g integar, in your case i which is first argument ) , Mutable object can be changed, infact every time you are calling you function f() the default argument values is being mutated.

So whats happening is that you first define values=[99] and Python "retains" the default value [99] to the function

Now with values.append(i) it is being mutated inside the function (values changes to [99,1], IT IS BEING MUTATED AS A DEFAULT VALUE AS WELL.

In the documentation, it clearly says that in case of mutable objects the default value is in effect modified

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

Mutable values can be very bad in some scenarios and for default values, do not use mutable default arguments, unless it is absolutely necessary

A.B
  • 20,110
  • 3
  • 37
  • 71