[Fixed] Accessing the index in ‘for’ loops in python

Question (Issue)

How do I access the index in a for loop?

xs = [8, 23, 45]

for x in xs:
    print("item #{} = {}".format(index, x))

Desired output:

item #1 = 8
item #2 = 23
item #3 = 45

Now we will see Solution for issue: Accessing the index in ‘for’ loops

Answer (solution)

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.

This question is answered By – Mike Hordecki

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0