Best way to have a for-loop index?

Scott David Daniels scott.daniels at acm.org
Thu Mar 9 19:41:04 EST 2006


andrewfelch at gmail.com wrote:
> I write a lot of code that looks like this:
> 
> for myElement, elementIndex in zip( elementList,
> range(len(elementList))):
>     print "myElement ", myElement, " at index: ",elementIndex
> 
> 
> My question is, is there a better, cleaner, or easier way to get at the
> element in a list AND the index of a loop than this?

     for elementIndex, myElement in enumerate(elementList):
         print "myElement ", myElement, " at index: ",elementIndex


--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list