Skip to content
Advertisement

Accessing the index in ‘for’ loops

How do I access the index while iterating over a sequence with a for loop?

JavaScript

Desired output:

JavaScript

Advertisement

Answer

Use the built-in function enumerate():

JavaScript

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.

Advertisement