1

I am new to python and have a difficulty getting an object to be stored and access in an array or a list in Python.

I've tried doing something like this:

class NodeInfo:
    def __init__(self, left, value, right):
        self.l = left
        self.r = right
        self.v = value

tree[0] = NodeInfo(0,1,2)

tree[0].l = 5
tree[0].r = 6
tree[0].v = 7

When I try to assign values to or try to read from the variable, I get the following error:

tree[0] = NodeInfo(0,1,2)
NameError: name 'tree' is not defined

What am I doing wrong, or is there a different way to assign and read objects from arrays or lists in Python.

Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88
jao
  • 1,194
  • 1
  • 11
  • 17
  • Unrelated, but you also might want to drop your old style class, and get a new style class. That is, `class NodeInfo:` becomes `class NodeInfo(object):`. Unless you're using Python 3 (then it won't matter as old style classes were dropped), but I'd still prefer to use the same convention. See [this](http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python). – John Doe Oct 28 '11 at 06:29

1 Answers1

8

You need to create list first and use append method to add an element to the end of it.

tree = []
tree.append(NodeInfo(0,1,2))

# or
tree = [NodeInfo(0,1,2)]
DrTyrsa
  • 31,014
  • 7
  • 86
  • 86