object's list index

Iain King iainking at gmail.com
Fri Mar 3 13:29:27 CET 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?

Um, one of us is being really really dense today :)  I hope it's not
me...
 what's wrong with:

i = 0
for object in list:
    objectIndex = i
    print objectIndex
    i += 1

Iain




More information about the Python-list mailing list