Why this local variable can keep its value in the function
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">&ldquo;Least Astonishment&rdquo; in Python: The Mutable Default Argument</a>  </p>
</blockquote>



<p>I recently met a problem in Python.
Code:</p>

<pre><code> def f(a, L=[]):
   L.append(a)
   return L

 print f(1)
 print f(2)
 print f(3)
</code></pre>

<p>the output would be </p>

<pre><code>[1]
[1, 2]
[1, 2, 3]
</code></pre>

<p>but why the value in the local list: L in the function f remains unchanged?
Because L is a local variable, I think the output should be:</p>

<pre><code>[1]
[2]
[3]
</code></pre>

<p>I tried another way to implement this function:
Code:</p>

<pre><code>def f(a, L=None):
  if L is None:
  L = []
  L.append(a)
  return L 
</code></pre>

<p>This time, the output is:</p>

<pre><code>[1]
[2]
[3]
</code></pre>

<p>I just don't understand why...
Does anyone have some ideas? many thanks.</p>
