S = 'test' offset = 0 # from w w w . ja va 2 s . c om for item in S: print(item, 'appears at offset', offset) offset += 1
enumerate function does the job for us.
It gives loops a counter without sacrificing the simplicity of automatic iteration:
S = 'test' for (offset, item) in enumerate(S): print(item, 'appears at offset', offset)
The enumerate function returns a generator object.
The generator object has a method called by the next built-in function, which returns an (index, value) tuple each time through the loop.
The for steps through these tuples automatically, which allows us to unpack their values with tuple assignment, much as we did for zip:
S = 'test' E = enumerate(S) # w w w . j ava 2s .c o m print( E ) print( next(E) ) print( next(E) ) print( next(E) )