Best way to have a for-loop index?
Michael Spencer
mahs at telcopartners.com
Thu Mar 9 19:43:50 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?
>
> TIA,
> Andrew
>
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
Michael
More information about the Python-list
mailing list