getting the index while iterating through a list

Steven Rumbalski srumbalski at copper.net
Wed May 12 11:30:05 EDT 2004


Fernando Rodríguez wrote:

> 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

Try enumerate:
>>> newList = [(i, element) for i, element in enumerate(aList)]

from Python-Docs-2.3/lib/built-in-funcs.html:

enumerate(iterable)
    Return an enumerate object. iterable must be a sequence, an iterator, or
    some other object which supports iteration. The next() method of the 
    iterator returned by enumerate() returns a tuple containing a count 
    (from zero) and the corresponding value obtained from iterating over 
    iterable. enumerate() is useful for obtaining an indexed series: (0,  
    seq[0]), (1, seq[1]), (2, seq[2]), .... New in version 2.3.

-- 
Steven Rumbalski
news|at|rumbalski|dot|com



More information about the Python-list mailing list