object's list index
Kent Johnson
kent at kentsjohnson.com
Fri Mar 3 07:36:58 EST 2006
William Meyer wrote:
> hi,
>
> I need to get the index of an object in a list. I know that no two objects
> in the list are the same, but objects might evaluate as equal. for example
>
> list = [obj1, obj2, obj3, obj4, obj5]
> for object in list:
> objectIndex = list.index(object)
> print objectIndex
>
> prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could loop
> through the list a second time comparing id()'s
>
> for object in list:
> objectIndex = 0
> for i in list:
> if id(object) == id(i):
> break
> objectIndex += 1
> print objectIndex
>
> but that seems like a real ugly pain. Somewhere, someplace python is keeping
> track of the current index in list, does anyone know how to access it? Or have
> any other suggestions?
>
Do you actually need to find the index of an arbitrary object in the
list or are you iterating the whole list and you need the list index
inside the list? In either case enumerate() is your friend. To find an
item by identity:
def index_by_id(lst, o):
for i, item in enumerate(lst):
if item is o:
return i
raise ValueError, "%s not in list" % o
If you just want the index available inside the loop, this replaces your
original loop:
for i, object in enumerate(lst):
print i
Kent
More information about the Python-list
mailing list