getting the index while iterating through a list
Peter Otten
__peter__ at web.de
Wed May 12 10:17:36 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()?
>>> aList = ["alpha", "beta", "gamma"]
>>> list(enumerate(aList))
[(0, 'alpha'), (1, 'beta'), (2, 'gamma')]
>>>
Peter
More information about the Python-list
mailing list