Reputation: 3
If I have a list of objects made from classes, is there a way to get the index of a particular object in that list?
I've tried using list.index like this:
obj_list = [object1(), object2()]
object1_index = obj_list.index(object1())
return object1_index
But this just returns a ValueError, saying that object1() is not in list, even though it is.
Upvotes: 0
Views: 610
Reputation: 71454
object1
is a constructor; each time you say object1()
you're constructing a new object of class object1
. Hence the object1()
in your index()
call does not refer to the same object as the one in obj_list
.
You could do something like:
next(i for i, x in enumerate(obj_list) if isinstance(x, object1))
to find the index of the first object in obj_list
that is an instance of object1
.
Upvotes: 1