'adding childern to tree stucture and print

I am trying to implement an n-arry tree based on this post : [here][1] and I am getting an error when trying to define a function that adds children:

    class node(object):
    def __init__(self, value, children = []):
        self.value = value
        self.children = children

    def __str__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__str__(level+1)
        return ret
    
    # trying to implement this method si that I can get rid of
    # calling root.children[0].children
    def add_child(self, obj):
        self.children.append(obj)
        
    def __repr__(self):
        return '<tree node representation>'

root = node('grandmother')
root.children = [node('daughter'), node('son')]
root.children[0].children = [node('granddaughter'), node('grandson')]
root.children[1].children = [node('granddaughter'), node('grandson')]
root.add_child([node((1)), node(2)]) # error 

print (root)

I want to be able to to create a tree and print it. [1]: Printing a Tree data structure in Python



Solution 1:[1]

You call add_child with an entire list object. Within add_child you use the method list.append which adds the entire list object to the list itself.

Solution 1: call add_child by specifying the nodes directly:

root.add_child(node((1))
root.add_child(node((2))

Solution 2: change the implementation of add_child by using list.extend instead of list.append. The former adds each element within the supplied argument to the list, while the latter adds the entire argument to the list.

def add_child(self, obj):
    self.children.extend(obj)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gerald Mayr