2
class Tree:
    def __init__(self, label, children = []):
        self.label = label
        self.children = children

t1 = Tree("START")
t2 = Tree("END")
t1.children.append(t2)

print t2.children
[<__main__.Tree instance at 0x005421C0>]

Why isn't t2.children empty?

siamii
  • 23,374
  • 28
  • 93
  • 143
  • Check out the above link: everyone is surprised by this issue eventually. For suggestions of Pythonic ways to fix it, check out http://stackoverflow.com/questions/366422/what-is-the-pythonic-way-to-avoid-default-parameters-that-are-empty-lists – David Robinson Oct 14 '13 at 04:12

1 Answers1

0

The problem is that the default value is executed only once - when the def statement is excuted. Thus, all instance objects' children are assigned the same list.

In short, the lists for t1 and t2 are the same list.

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95