object's list index

Iain King iainking at gmail.com
Fri Mar 3 14:03:22 CET 2006


Iain King wrote:
> Iain King wrote:
> > 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
>
> Reading it again, I'm thinking it probably is me...
>
> If you aren't looking them up sequentially then I think your second
> example is the only way.  You can make it a little prettier by using
> 'object is i' rather than 'id(object) == id(i)'.
> I think python only stores lists one way - i.e. each index maps to it's
> value, but no backwards trace is kept from value to index.
>
> Iain

OTOH, if memory is not an issue, you can create a lookup yourself:

def createLookup(l):
    d = {}
    for index in xrange(len(l)):
        objID = id(l[index])
        d[objID] = index
    return d

lookup = createLookup(list)
for i in list:
    objectIndex = lookup[id(i)]
    print objectIndex


Iain




More information about the Python-list mailing list