Something in the function tutorial confused me.

Lee Fleming countblabula at yahoo.com
Mon Aug 6 08:50:24 CEST 2007

```Hello,
I have a simple question. Say you have the following function:

def f(x, y = []):
y.append(x)
return y

print f(23)  # prints [23]
print f(42)  # prints [23, 42]

As far as I understand, the default value y, an empty list, is created
when the def statement evaluates. With this thought in mind, the above
calls
to f make sense.

But this, the code that "fixes" the list accumulation confounds me:
def  f(x, y=None):
if y is None: y = []
y.append(x)
return y

print f(23)  # prints [23]
print f(42)  # prints [42]

Why didn't the second call to f, f(42) return [23, 42]?
As I understand it, y is only None at the beginning of f(23).
Then y changes from None to 23. When f ends, doesn't y still have 23
in it,
just as it did in the first function I discussed?
And if y has 23 in it, won't the second call to f not execute what's
in the if statement?

In other words, what's going on here? How is it that y accumulates
argument values between function calls in the first function, but
doesn't in the second one?

```