I have a list of all instances of a class. I am tring to find out the index of the instance in that list given an attribute value.
for eg. I have the following code:
class Test():
all_objects=[]
def __init__(self,name,age):
self.name = name
self.age = age
Test.all_objects.append(self)
Test("joe",23)
Test("kate",16)
Test("adam",56)
#this is ugly ..
for ind,item in enumerate(Test.all_objects):
if item.name == 'joe':
print(ind)
I can find the index of the instance by iterating over each element in the list. Is there a better way to do this? (perhaps using the index() method somehow)
CLARIFICATION:
I was looking for a way to do this without having to iterate over the all_objects list. Looking at the comments and answers below, it seems like there might not be a way around this.
I thank you all for confirming this for me.
[obj.name for obj in Test.all_objects].index('joe')?all_objects?