0

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.

4
  • 1
    [obj.name for obj in Test.all_objects].index('joe')? Commented Dec 1, 2021 at 12:59
  • 2
    No way to do it without iterating. Commented Dec 1, 2021 at 13:05
  • 2
    If instance names are supposed to be unique, maybe you want to use a dictionary instead of a list for all_objects? Commented Dec 1, 2021 at 13:17
  • 1
    it is not ugly - it is very readable - and I use only this method as preferred. Commented Dec 1, 2021 at 14:03

2 Answers 2

1

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.