Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading