Possible Duplicate:
Accessing the index in Python for loops
I wonder: does Python have something like?
for (i=0; i < length; i += 1){ .... }
Of course, I might say
i = 0
for item in items:
#.....
i += 1
but I think there should be something similar to for(i = 0;...), shouldn’t it?
Use the
enumerate()function:or use
range():(On python 2 you’d use
xrange()instead).range()let’s you step throughiin steps other than1as well:You usually don’t need to use an index for sequences though; not with the
itertoolslibrary or thereversed()function; most usecases for ‘special’ index value ranges are covered: