The Pointer
The Pointer

Reputation: 2386

Iterating through a list of objects that belong to an object

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?

Upvotes: 0

Views: 42

Answers (4)

Macosso
Macosso

Reputation: 1439

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

Upvotes: 1

liakoyras
liakoyras

Reputation: 1185

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)

Upvotes: 0

Buzz
Buzz

Reputation: 1422

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}')

Upvotes: 2

itismoej
itismoej

Reputation: 1847

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)

Upvotes: 0

Related Questions