Iterating through a list of objects that belong to an object

Question:

I am trying to build my own network of nodes and analyse it. I have a Node class and a Network class:

class Node():

    def __init__(self, ID, team):
        self.ID = ID
        self.team = team
        self.edge = (None, None)


class Network():

    def __init__(self, number_of_green_nodes):
        self.green_network = [Node(ID = i, team = "Green") for i in range(number_of_green_nodes)]

I then create a network object, network1, consisting of 10 Node objects:

network1 = network.Network(10)

I now want to iterate through the network’s list of nodes, and access some attributes of the Node objects. For instance, to access the ID attribute of each of the nodes, I do the following:

for i in network1.green_network:
    print(network1.green_network[i].ID)

But this results in the following error:

TypeError: list indices must be integers or slices, not Node

So how is this done?

Asked By: The Pointer

||

Answers:

You have used the for-each notation; so the i is a Node not an integer.

for node in network1.green_network:
    print(node.ID)

If you want to mutate them:

for i in range(10):
    print(network1.green_network[i].ID)

Answered By: Mohammad Jafari

network1.green_network is a list and with the for cycle you’re directly iterating through that list:

for node in network.green_network:
    print(node.ID)

Or, if you need the index, that is useless since it is the same as the ID for how you initialize the network:

for i, node in enumerate(network.green_network):
    print(f'Node in position {i} has ID {node.ID}')
Answered By: Buzz

Your variable i iterates through the list of nodes. Thus, the values it takes are of type Network, since this is what the network1.green_network list contains.

The error happens because you try to index a list using data of type Network as an index, which is not possible, it needs to be of type int.

In order to access both the Network objects and their index, you can try:

for node, index in zip(network1.green_network, range(len(network1.green_network))):
    print(node.ID)
    print(network1.green_network[index].ID)
Answered By: liakoyras
for i in range(len(network1.green_network)):
    print(network1.green_network[i].ID)
Answered By: Macosso
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.