Python object identity
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">“Least Astonishment” in Python: The Mutable Default Argument</a>  </p>
</blockquote>



<p>I have the following Python code:</p>

<pre><code>class Node(object):
    def __init__(self, name, children = []):
        self.name = name
        self.children = children

    def add_child(self, child):
        self.children.append(child)

    def __str__(self):
        return self.name

def create_tree(num_vertices):
    vs = [Node(str(i)) for i in range(num_vertices)]
    for i in range(num_vertices):
        if 2 * i + 1 &lt; num_vertices:
            vs[i].add_child(vs[2 * i + 1])
        if 2 * i + 2 &lt; num_vertices:
            vs[i].add_child(vs[2 * i + 2])

    return vs[0]

def bfs(top_node, visit):
    """Breadth-first search on a graph, starting at top_node."""
    visited = set()
    queue = [top_node]
    while len(queue):
        curr_node = queue.pop(0)   # Dequeue
        visit(curr_node)           # Visit the node
        visited.add(curr_node)

        # Enqueue non-visited and non-enqueued children
        queue.extend(c for c in curr_node.children
                     if c not in visited and c not in queue)

def visit(tree):
    print tree
</code></pre>

<p>Now I make the following calls in IDLE:</p>

<pre><code>&gt;&gt;&gt; bfs(create_tree(3), visit)
0
1
2
&gt;&gt;&gt; bfs(create_tree(3), visit)
0
1
2
1
2
</code></pre>

<p>Even though I'm trying to create a new tree each time, I seem to be ending up with the same tree each time (with new nodes being added each time).  Why is that?  In create_tree, I'm creating a new list vs with each function call.</p>

<p>(By the way, this is not homework.  It is Exercise 4.2 in <em>Think Complexity</em>, which I'm reading for fun, and the exercise is not to figure out why "[e]ven though I'm trying to create a new tree each time, I seem to be ending up with the same tree each time".  (The problem is to find out why the bfs code is inefficient and I know the answer to that.))</p>
