object's list index

William Meyer wmmeyer at gmail.com
Fri Mar 3 13:15:27 CET 2006


    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):
        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?

More information about the Python-list mailing list