S = 'test' offset = 0 # ww w.j av a 2 s . co m 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 ava2s . co m print( E ) print( next(E) ) print( next(E) ) print( next(E) )