Accessing the index in ‘for’ loops

Use the built-in function enumerate():

for idx, x in enumerate(xs):
    print(idx, x)

It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable.

Check out PEP 279 for more.

Leave a Comment