oadams
oadams

Reputation: 3087

Odd behaviour with simple tree implementation in python

class Node:
    children = {}

sequence = [1,2,3,4,5]

tree = Node()
node = tree
for item in sequence:
    if item not in node.children:
        node.children[item] = Node()
    node = node.children[item]

print tree.children.keys()

I want the above code to output [1], however it outputs [1, 2, 3, 4, 5]. Why is this, and how would I go about fixing it?

Upvotes: 0

Views: 138

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798556

Node.children is a class attribute. Make it an instance attribute instead.

class Node:
  def __init__(self):
    self.children = {}

Upvotes: 7

Related Questions