Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I have the following Python 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 < num_vertices:
vs[i].add_child(vs[2 * i + 1])
if 2 * i + 2 < 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
Now I make the following calls in IDLE:
>>> bfs(create_tree(3), visit)
0
1
2
>>> bfs(create_tree(3), visit)
0
1
2
1
2
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.
(By the way, this is not homework. It is Exercise 4.2 in Think Complexity, 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.))
That is because if you set in init
children = []it does not create a new list each time, it creates a list the first time and the other times uses the same one; that explains the behavior. in these cases the best thing to do is to write