Skip to content
Advertisement

How can I get attributes of induvidual items in a list of Objects in Python?

I have a list of objects known as Civilizations and initialized as

JavaScript

I also have a class Civilization and class Mothership as

JavaScript

Printing (a) gives us <__main__.Mothership object at 0x0000029412E240A0> twice as a result, and x ends up looking like [300,300]. Is there a way to iterate over the objects and obtain their individual attributes? I am trying to get x to look like [300, 350].

Thank You for your help!

Advertisement

Answer

Issue is with the below two lines of code.

JavaScript

mothership list in Civilizations class will be appended with two objects. Civilizations.mothership = [ obj_orange, obj_yellow ]

Since your mothership list having two values in index of 0 & 1. In your code you are using only index 0 to retrieve the value throughout the loop. Your loops runs twice and returns the same object (obj_orange) twice.

Either you have to retrieve both the values from index 0 & 1 like below

JavaScript

Or simply you can use ‘enumerate’ which is very good practice in situations like where you don’t know the number of elements in a list.

JavaScript

where i = index number , t = value

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement