title: __init__(self, list=[]) only makes one list rather than a new one for every instantiation?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://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>Why is this:</p>
  
  <pre><code>class Test:
      def __init__(self, items=[]):
          self.items=items
  </code></pre>
  
  <p>different than this:</p>
  
  <pre><code>class Test2:
      def __init__(self, items=None):
          if items:
             self.items=items
          else:
             self.items = []
  </code></pre>
  
  <p>Those seem like they should do the same thing, but:</p>
  
  <pre><code>&gt;&gt;&gt;t = Test()
  &gt;&gt;&gt;t.items.append("stuff")
  &gt;&gt;&gt;t.items
  ['stuff']
  &gt;&gt;&gt;t2 = Test()
  &gt;&gt;&gt;t2.items
  ['stuff']
  </code></pre>
  
  <p>Ok, so with Test(), there's only one list being created, and everyone is accessing it, despite what I thought was explicitly setting items in the constructor and not putting it in the class namespace. But with Test2:</p>
  
  <pre><code>&gt;&gt;&gt;t = Test2()
  &gt;&gt;&gt;t.items.append("stuff")
  &gt;&gt;&gt;t.items
  ['stuff']
  &gt;&gt;&gt;t2 = Test2()
  &gt;&gt;&gt;t2.items
  []
  </code></pre>
  
  <p>That's working the way I expect. Test also doesn't share data between instances if you call it explicitly with an empty list rather than let the default do the work, as in t = Test([]).</p>
  
  <p>So is it that defaults are only created once at compile time, rather than dynamically? Is that only true for class definitions, not for functions in general, or is this a more general pitfall for using defaults in argument lists? (Answer: it happens for functions, too.)</p>
  
  <p>Note that I tested this with a string instead of a list, and got expected behavior where data was not shared between instances. But it does happen with dicts as well.</p>