getting an item's list index

Roel Schroeven j4nff5m02 at sneakemail.com
Sat Apr 19 09:19:29 EDT 2003


Michael Anckaert wrote:
> Hello all,
> 
> I have a list called contents. If one of the elements has the value
> "item1" for example, how can I get that elements index?
> 
> 
> for item in contents:
> 	# here I need to get that items index
> 

One could do:

for item in contents:
	index = contents.index(item)

But that's quite inefficient (0(n^2) I think). If you need the index 
anyway, I think you'd better do it like this:

for index in range(len(contents)):
	print index, contents[index]


-- 
"Codito ergo sum"
Roel Schroeven
http://roelschroeven.net





More information about the Python-list mailing list