enumerate
S = 'test' offset = 0 # w w w.ja va 2s .c o 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) # from w w w. j a va 2s.c o m print( E ) print( next(E) ) print( next(E) ) print( next(E) )