EasilyBaffled
EasilyBaffled

Reputation: 3882

Finding instance of Object type in list

I have a situation like the code below. I want to find the index of the first instance of the object A. What is the fastest way I can do that?

I know there are a lot of ways to go through the entire list and find it, but is there a way to stop the search once the first one is found?

class A():
    def __init__(self):
        self.a = 0
    def print(self):
        print(self.a)

l = [0, 0, A(), 0, A(), 0]
print(l.index(type(A))) # this does not work

Upvotes: 0

Views: 135

Answers (3)

Joran Beasley
Joran Beasley

Reputation: 114038

class A():
    def __init__(self):
        self.a = 0
    def __eq__(self,other): #this overrides the equality check
        if isinstance(other,A):
           return self.a==other.a
    def print(self):
        print(self.a)

l = [0, 0, A(), 0, A(), 0]
print(l.index(A()))#now this should work
print A() in l

a1 = A()
a2 = A()
a1 == a2 #True
a1.a = 2
a1 == a2 #False
a2.a = 2
a1 == a2 #True
a2.a = 5
a1 < a2 #Error we would need to overload __cmp__ or __lt__ methods for this to work

Upvotes: 2

Samy Arous
Samy Arous

Reputation: 6814

The most obvious way:

for index, value in enumerate(l):
    if isinstance(value,A):
        return (index, value)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124178

You have to test each object; use a list comprehension and enumerate() to get all matching indices:

[i for i, ob in enumerate(l) if isinstance(ob, A)]

or to get the first index, use next() and a generator expression:

next((i for i, ob in enumerate(l) if isinstance(ob, A)), None)

Demo:

>>> [i for i, ob in enumerate(l) if isinstance(ob, A)]
[2, 4]
>>> next((i for i, ob in enumerate(l) if isinstance(ob, A)), None)
2

Upvotes: 3

Related Questions