site logo

Ask. Code. Learn. Grow with the Developer Community.


Category: (All)
❮  Go Back

Python For Loop with Index – Using enumerate()

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


Python For Loop with Index Using enumerate

coldshadow44 on 2025-10-13





Make a comment


Showing comments related to this post.

_

2025-10-14

The Pythonic way is to use the built-in enumerate() function:


xs = [8, 23, 45]

for idx, x in enumerate(xs, start=1):
print("item #{} = {}".format(idx, x))


Output:

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


Notes:

  1. enumerate(xs) returns pairs (index, value) for each item in the sequence.
  2. start=1 ensures the index begins at 1 instead of the default 0.
  3. Avoid manually indexing with for i in range(len(xs)) — it’s less readable and considered un-Pythonic.





Member's Sites: