getting the index while iterating through a list

Holger Türk htx1 at gmx.de
Wed May 12 10:15:49 EDT 2004



Fernando Rodríguez wrote:
> 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()?

Not with map. Use zip:

newList = zip (range (len (aList)), aList)

Greetings,

Holger




More information about the Python-list mailing list