object's list index

W

William Meyer

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?
 
I

Iain King

William said:
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
 
K

Kent Johnson

William said:
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
 
W

William Meyer

Iain King said:
what's wrong with:

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

Iain

The issues with that is you might have a complex structure below the for object
in list: with lots of continues or breaks and you don't want to have to remember
to change the index everytime. There is an old pep
(http://www.python.org/peps/pep-0212.html) that describes some proposed
solutions, but I was wondering if anything has happened since aug 2000. I might
just use the

for objectIndex in range(len(list)):
e = list[objectIndex]

solution, though its ugly too.
 
S

Sybren Stuvel

Iain King enlightened us with:
i = 0
for object in list:
objectIndex = i
print objectIndex
i += 1

Why not:

for index, object in enumerate(list):
print index

Sybren
 
I

Iain King

Iain said:
William said:
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
 
W

William Meyer

Kent Johnson said:
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

Thanks, both you and Fredrik Lundh suggested enumerate, which seems like the
best solution. I just need the index inside the loop, but thanks again for both
solutions.
 
F

Felipe Almeida Lessa

Em Sex, 2006-03-03 às 12:48 +0000, William Meyer escreveu:
Thanks, both you and Fredrik Lundh suggested enumerate, which seems like the
best solution. I just need the index inside the loop, but thanks again for both
solutions.

You should *always* use enumerate. "list.index" has a high cost and
shouldn't be used that way.

--
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

-- Sun Tzu, em "A arte da guerra"
 
I

Iain King

Iain said:
Iain said:
William said:
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
 
S

Steven D'Aprano

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.

Python lists are arrays of pointers to objects. The objects themselves
have no clue what lists they belong to, or what position they are in.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,289
Messages
2,571,435
Members
48,120
Latest member
Natbelix

Latest Threads

Top