By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,689 Members | 1,787 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,689 IT Pros & Developers. It's quick & easy.

object's list index

P: n/a
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?

Mar 3 '06 #1
Share this Question
Share on Google+
9 Replies


P: n/a

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

Mar 3 '06 #2

P: n/a
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?

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
Mar 3 '06 #3

P: n/a
Iain King <iainking <at> gmail.com> writes:
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.
Mar 3 '06 #4

P: n/a
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
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Mar 3 '06 #5

P: n/a

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

Mar 3 '06 #6

P: n/a
Kent Johnson <kent <at> kentsjohnson.com> writes:
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.

Mar 3 '06 #7

P: n/a
Em Sex, 2006-03-03 √*s 12:48 +0000, William Meyer escreveu:
Kent Johnson <kent <at> kentsjohnson.com> writes:
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.


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"

Mar 3 '06 #8

P: n/a

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

Mar 3 '06 #9

P: n/a
On Fri, 03 Mar 2006 04:48:20 -0800, Iain King wrote:
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.
--
Steven.

Mar 4 '06 #10

This discussion thread is closed

Replies have been disabled for this discussion.