jao
jao

Reputation: 1194

Store and Retrieve Objects from Python Lists

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.

Upvotes: 1

Views: 8065

Answers (1)

DrTyrsa
DrTyrsa

Reputation: 31951

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)]

Upvotes: 8

Related Questions