getting the index while iterating through a list

Hornberger, Chris Chris.Hornberger at blackrock.com
Wed May 12 10:36:45 EDT 2004


As long as you need the index and the element, wouldn't it just be better to iterate the list by the index?

for i in range( len( list ) ):
	print "index: %d" % d
	print "Element: %s " % list[i]

?

--------------------------
Chris Hornberger
Blackrock - 302.797.2318
chris.hornberger at blackrock.com

Card carrying MSDN member since 2004.
No, really. I've got the card to prove it.


-----Original Message-----
From: python-list-bounces+chris.hornberger=blackrock.com at python.org
[mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On
Behalf Of Fernando Rodríguez
Sent: Wednesday, May 12, 2004 10:01 AM
To: python-list at python.org
Subject: getting the index while iterating through a list


Hi,

While iterating through a list I'd like to know not just the current element,
but also its index. Is there a better way than this:

i = 0
newList = []
for element in aList:
  newList.append((i, element))
  i += 1

Is there a more elegant way of doing this with for? And with map()?

Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list