Vector of objects in Python

Asked

Viewed 1,322 times

0

I want to create a Node class, and one of its attributes is a Nodes vector (as in a chained list). Since Python does not declare the type of attribute, I have no idea dd how to do.

1 answer

2


In a normal chained list each node has an attribute that represents the next node only and not a list:

class Nodo:
    def __init__(self, valor):
        self.valor = valor
        self.prox = None

If in your particular case you need to have an attribute which is a list for the various nodes you can do so:

class Nodo:
    def __init__(self, valor):
        self.valor = valor
        self.nodos = [] #lista de Nodos

Now in this list will add each Nodo as it needs using for example the function append:

self.nodos.append(Nodo(10))

Python does not declare the type of the attribute, but the type is built according to its value. This means that if you want to have a list of elements of a certain type, you only need to add such elements to the list.

  • Thanks, it was very helpful. in this case how do I check if a list position is empty?

  • 1

    @Leonardofurtado You’re welcome. It doesn’t exactly work that way. When removing a particular node from the list it is as if everyone else walks back one position to occupy the space left. So the list actually never has holes.

  • I get it, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.