getting the index while iterating through a list

François Pinard pinard at iro.umontreal.ca
Wed May 12 10:48:07 EDT 2004


[Fernando Rodríguez]
> 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()?

Hi, Fernando.  You may write something like:

    newList = []
    for i, element in enumerate(aList):
      newList.append((i, element))

or even simpler:

    newList = list(enumerate(aList))

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list