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.

Answer from Mike Hordecki on Stack Overflow
🌐
Trey Hunner
treyhunner.com › 2016 › 04 › how-to-loop-with-indexes-in-python
How to loop with indexes in Python
We can loop over this range using Python’s for-in loop (really a foreach). This provides us with the index of each item in our colors list, which is the same way that C-style for loops work.
Top answer
1 of 16
9259

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.

2 of 16
1368

Using a for loop, how do I access the loop index, from 1 to 5 in this case?

Use enumerate to get the index with the element as you iterate:

for index, item in enumerate(items):
    print(index, item)

And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:

count = 0 # in case items is empty and you need it after the loop
for count, item in enumerate(items, start=1):
    print(count, item)

Unidiomatic control flow

What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:

index = 0            # Python's indexing starts at zero
for item in items:   # Python's for loops are a "for each" loop 
    print(index, item)
    index += 1

Or in languages that do not have a for-each loop:

index = 0
while index < len(items):
    print(index, items[index])
    index += 1

or sometimes more commonly (but unidiomatically) found in Python:

for index in range(len(items)):
    print(index, items[index])

Use the Enumerate Function

Python's enumerate function reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an enumerate object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:

for index, item in enumerate(items, start=0):   # default is zero
    print(index, item)

This code sample is fairly well the canonical example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.

Getting a count

Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with 1 and the final number will be your count.

count = 0 # in case items is empty
for count, item in enumerate(items, start=1):   # default is zero
    print(item)

print('there were {0} items printed'.format(count))

The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.


Breaking it down - a step by step explanation

To break these examples down, say we have a list of items that we want to iterate over with an index:

items = ['a', 'b', 'c', 'd', 'e']

Now we pass this iterable to enumerate, creating an enumerate object:

enumerate_object = enumerate(items) # the enumerate object

We can pull the first item out of this iterable that we would get in a loop with the next function:

iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)

And we see we get a tuple of 0, the first index, and 'a', the first item:

(0, 'a')

we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:

index, item = iteration
#   0,  'a' = (0, 'a') # essentially this.

and when we inspect index, we find it refers to the first index, 0, and item refers to the first item, 'a'.

>>> print(index)
0
>>> print(item)
a

Conclusion

  • Python indexes start at zero
  • To get these indexes from an iterable as you iterate over it, use the enumerate function
  • Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:

So do this:

for index, item in enumerate(items, start=0):   # Python indexes start at zero
    print(index, item)
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-range.html
Python range() Function
>>> s = 'Python' >>> len(s) 6 >>> for i in range(len(s)): ... print(i, s[i]) ... 0 P 1 y 2 t 3 h 4 o 5 n · The input to the range() must be int. The output of range() is an "iterable" producing the series of int values. The iterable is similar to a list, but more lightweight.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python – access index in for loop with examples
Python - Access Index in For Loop With Examples - Spark By {Examples}
May 31, 2024 - Note that for every iteration the index will be increased and returned with the corresponding item. # Using range() to access both index & item courses = ['java','python','pandas','sparks'] for index in range(len(courses)): item = courses[index] print(index, item)
🌐
TutorialKart
tutorialkart.com › python › python-for-loop › python-for-loop-with-index
Python For Loop with Index - Examples
November 30, 2020 - list_1 = ["apple", "banana", "orange", "mango"] for index in range(len(list_1)): print(index, list_1[index]) ... Concluding this Python Tutorial, we learned how to access index of the iterable in for loop during each iteration.
🌐
Better Programming
betterprogramming.pub › stop-using-range-in-your-python-for-loops-53c04593f936
Stop Using range() in Your Python for Loops | by Jonathan Hsu | ...
January 20, 2020 - Stop Using range() in Your Python for Loops How to access the current index using the enumerate() function The for loop. It is a cornerstone of programming — a technique you learn as a novice and …
Find elsewhere
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.RangeIndex.html
pandas.RangeIndex — pandas 3.0.1 documentation
class pandas.RangeIndex(start=None, stop=None, step=None, dtype=None, copy=False, name=None)[source]# Immutable Index implementing a monotonic integer range.
🌐
W3Schools
w3schools.com › python › python_lists_access.asp
Python - Access List Items
When specifying a range, the return value will be a new list with the specified items. ... thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) Try it Yourself » · Note: The search will start at index 2 (included) and end at index 5 (not included). Remember that the first item has index 0.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-access-index-in-for-loop-python
How to Access Index using for Loop - Python - GeeksforGeeks
July 23, 2025 - Explanation: range(len(data)) generates index numbers. data[i] fetches the character at each index. The enumerate() function returns both the index and the value during iteration, making the loop cleaner and more Pythonic.
🌐
Rollbar
rollbar.com › home › how to fix python’s “list index out of range” error in for loops
How to Fix Python’s “List Index Out of Range” Error in For Loops | Rollbar
March 25, 2025 - This error means Python can't find the list position you're asking for. Fix it with enumerate(), proper length checks, or by using -1 to safely get the last item.
🌐
Codecademy
codecademy.com › forum_questions › 558ae27493767630000004f5
"for x in list" verses "for x in range(len(list)) | Codecademy
The len() will pass its result - which is 3 - as an argument to the function range(). So it is the same as our first loop which had range(3). This is very useful when you want to modify the list at certain positions. To make a mabye not so useful illustration: my_list = ['a', 'b', 'c', 'd', 'e' ] for index in range(len(my_list)): if my_list[index] in 'aeiou': my_list[index] = 'vowel' else: my_list[index] = 'consonant' my_list == ['vowel' 'consonant', 'consonant', 'consonant', 'vowel' ] #true
🌐
Python Tutorial
pythontutorial.net › home › python basics › python for loop with range
A Basic Guide to Python for Loop with the range() Function
March 26, 2025 - Summary: in this tutorial, you’ll learn about the Python for loop and how to use it to execute a code block a fixed number of times. In programming, you often want to execute a block of code multiple times. To do so, you use a for loop. The following illustrates the syntax of a for loop: for index in range(n): statementCode language: Python (python)
🌐
Python Guides
pythonguides.com › python-for-loop-index
How to Use Python For Loop with Index
October 14, 2025 - The enumerate() function is the best and most Pythonic way to use a for loop with an index. The range() and len() combo is still useful in older codebases.
🌐
Programiz
programiz.com › python-programming › examples › index-for-loop
Python Program to Access Index of a List Using for Loop
my_list = [21, 44, 35, 11] for index in range(len(my_list)): value = my_list[index] print(index, value)
🌐
Note.nkmk.me
note.nkmk.me › home › python
Python for Loop (With range, enumerate, zip) | note.nkmk.me
August 18, 2023 - How to slice a list, string, tuple in Python · You can use the range() function to create a counter (index) for a for loop. for i in range(3): print(i) # 0 # 1 # 2 · source: for_range.py · In Python 3, range() creates a range object, and ...
🌐
PYnative
pynative.com › home › python › python range() explained with examples
Python range() Function Explained with Examples
March 17, 2022 - from itertools import chain # Concatenate ranges new_range = chain(range(5), range(5, 10)) for num in new_range: print(num, end=' ') # Output 0 1 2 3 4 5 6 7 8 9Code language: Python (python) Run · Built-in function range() is the constructor that returns a range object, this range object can also be accessed by its index number using indexing and slicing.