Best way to have a for-loop index?
Terry Hancock
hancock at anansispaceworks.com
Fri Mar 10 03:07:44 EST 2006
On 9 Mar 2006 16:32:24 -0800
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?
In fact it is so common a need, there is a built-in
function called "enumerate" that does the 'zip' for
you:
for elementIndex, myElement in enumerate(elementList):
print "myElement ", myElement, " at index: ",elementIndex
--
Terry Hancock (hancock at AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com
More information about the Python-list
mailing list