Home > OS >  How to find the index of a class instance in a list from the attribute
How to find the index of a class instance in a list from the attribute

Time:12-01

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.

CodePudding user response:

Using functional programming ⬇

my_filter = filter(lambda x: x[1].name == 'joe', enumerate(Test.all_objects))
print(next(my_filter)[0])

One liner ⬇

print(next(filter(lambda x: x[1].name == 'joe', enumerate(Test.all_objects)))[0])

One liner and prints Not Found when the specified instance is not found ⬇

print(next(filter(lambda x: x[1].name == 'joe', enumerate(Test.all_objects)))[0], 'Not Found')

CodePudding user response:

If you want to search many times maybe create a dict with the name and its associated object:

objects = {i.name: i for i in Test.all_objects}

Now you can access the objects by its name:

a = objects['joe']

Obviously that doesn't work if there are multiple objects with the same name you can overcome that by using a defaultdict:

from collections import defaultdict

objects = defaultdict(list)
for i in Test.all_objects:
    objects[i.name].append(i)

Now every key has a list of objects.

  • Related