473,473 Members | 1,709 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

object's list index

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
9 17381

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

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

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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Poewood | last post by:
Okay here are four classes for a pocket pc program: Input, fpositional, ComboBoxArray and TextBoxArray. The "input" class is the form. I use the fpositional class to handle most of the functions...
0
by: a | last post by:
Q. Unable to get a Profile custom (object) collection to bind to GridView,etc (IList objects)? This is my first custom object so I may be doing something rather simple, wrong, or it may be...
8
by: a | last post by:
I'm trying to save data from a custom object into the profile object, but it is not structured the way that I want. I'm trying to get the custom object to serialize as xml to a Profile object...
0
by: a | last post by:
I need to create an instance of a custom object 'School.Teacher' and use it in a Profile object. I'm developing a bad case of "Pretzel Logic" thinking about this. Filling the custom object ...
6
by: Doug | last post by:
Hi, I want to create a collection of objects that will be used as a property of another object. So for example if I had a Customer object, I would like to have an AddressCollection property...
2
by: Ralph | last post by:
Hi I don't understand why it's not working: function schedule(imTop){ this.tdImagesTop = imTop; } schedule.prototype.selectEl = function() { alert(this.tdImagesTop);
7
by: Sehboo | last post by:
We have several generic List objects in our project. Some of them have about 1000 items in them. Everytime we have to find something, we have to do a for loop. There is one method which does the...
3
by: Eric Mahurin | last post by:
Is there a standard way to get a descriptor object for an arbitrary object attribute - independent of whether it uses the descriptor/ property protocol or not. I want some kind of...
1
by: Øyvind Isaksen | last post by:
I try to make my own ArticleAttribute object and ArticleAttributeCollection, and add data to this Collection. It almost works, but the problem is that each time I add an ArticleAttribute to my...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.