QN: Python: Looping through sequence and indices simultaneously

I started programming in python from the days of 1.5.2, and have not kept up to date with some of the new features. Two features that caught me by surprise:

enumerate()  # builtin function
"...".format() # String method

enumerate() takes a list an returns an interator tuple (index,value) as it goes along the sequence. Very handy and obviates the need for the very messy:

for i in range(len(L)):
    print "I need the index {0} and the item {1} at the same time".format(i,L[i])

This illustrates the second new feature I just realized, the .format() method. This apparently replaces the ‘%’ operator and allows formatted strings to include positional replacement strings using {idx} notation.

Comments are closed.