HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How can I access the index value in a 'for' loop?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
indexhowaccessvaluetheforcanloop

Problem

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

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.

Code Snippets

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

Context

Stack Overflow Q#522563, score: 9258

Revisions (0)

No revisions yet.