object's list index

Sebastjan Trepca trepca at gmail.com
Fri Mar 3 07:30:25 EST 2006


Um, what about:

for oindex in xrange(len(list)):
   object = list[oindex]
   print oindex

You can't create a generic function for this.

Sebastjan

On 3/3/06, William Meyer <wmmeyer at gmail.com> 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?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list