How do I access the index while iterating over a sequence with 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
listloopspython
How do I access the index while iterating over a sequence with 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
Best Answer
Use the built-in function
enumerate()
: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.