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
Top answer
1 of 16
9281

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
1374

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)
🌐
Trey Hunner
treyhunner.com › 2016 › 04 › how-to-loop-with-indexes-in-python
How to loop with indexes in Python
April 25, 2016 - 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.
Discussions

Why iterate over an array using the index?
You do it if there is something in your loop that will use an index rather than the elements of the array. For instance, sometimes you want to sample something from another array that is not your loop array A cleaner way to do it is by using enumerate function for i, item in enumerate(array): The index gets assigned to i and whatever element of the array gets assigned to item. This may also be a bad habit from Matlab, people that come from Matlab are more used to looping over indexes. More on reddit.com
🌐 r/learnpython
57
46
April 22, 2023
Going through arrays with for loops in Python - Stack Overflow
Given an array called array, loop through all of its elements and print them out. I have tried to use the following code but it is giving me the error TypeError: list indices must be integers, not ... More on stackoverflow.com
🌐 stackoverflow.com
For loop in Python with indices - Stack Overflow
I'm making the transition from java to python and I'm confused about how for loops work in python. I know basically all for loops in python are for-each loops, but that's not what I need. I've buil... More on stackoverflow.com
🌐 stackoverflow.com
How to loop through indices in Python? - Stack Overflow
I'm trying to run a for loop in python that looks like this: data = np.linspace(0.5, 50, 10) output = [] for i in data: x = data[i] - data[i+1] output.append(data) ... IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-access-index-in-for-loop-python
How to Access Index using for Loop - Python - GeeksforGeeks
July 23, 2025 - data = ["java", "python", "HTML", "PHP"] print("Indices:", [i for i in range(len(data))]) print("Elements:", [data[i] for i in range(len(data))]) ... Explanation: [i for i in range(len(data))] creates a list of indices.
🌐
CodeRivers
coderivers.org › blog › python-looping-through-array
Python Looping Through Arrays: A Comprehensive Guide - CodeRivers
July 21, 2026 - To loop through an array using a while loop, you need to keep track of the index.
🌐
Tutorialspoint
tutorialspoint.com › python › python_loop_arrays.htm
Python - Loop Arrays
When you are using this loop with arrays, initialize a loop variable before entering the loop. This variable often represents an index for accessing elements in the array. Inside the while loop, iterate over the array elements and manually update ...
🌐
Python Guides
pythonguides.com › python-for-loop-index
Python For Loop with Index (enumerate and start)
October 14, 2025 - Below: the start argument, what happens with dictionaries, and the bug that appears when you remove items while looping. Everything ran on Python 3.12.5. enumerate() adds the position without changing anything else. ... fruits = ["apple", "pear", "plum"] for index, fruit in enumerate(fruits): print(index, fruit) print() print("enumerate hands back a position and an item on every pass,") print("so there is no indexing and nothing to count yourself.")
Find elsewhere
🌐
StrataScratch
stratascratch.com › blog › mastering-loop-iterations-python-for-loop-index-explained
Mastering Loop Iterations: Python For Loop Index Explained - StrataScratch
October 17, 2024 - Have you ever noticed how Python's for loops make handling sequences a breeze? They automatically assign each element—such as a row in your dataset—to a loop variable. You can then use this variable inside your loop for various operations on each element. Maybe you want to see how clients' ages vary. Let’s Loop through client data and print their ages. Here is the code. for index, row in client_data.iterrows(): print(f"Client ID: {row['client_id']}, Age: {row['client_age']}") if index == 4: # Limit to 5 rows break
🌐
Python Morsels
pythonmorsels.com › looping-with-indexes
Looping with indexes - Python Morsels
October 8, 2020 - Python's built-in enumerate function is the preferred way to loop while counting upward at the same time. You'll almost always see tuple unpacking used whenever enumerate is used.
🌐
NumPy
numpy.org › doc › stable › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.5 Manual
With this looping construct, the current value is accessible by indexing into the iterator. Other properties, such as tracked indices remain as before.
🌐
DEV Community
dev.to › lifeportal20002010 › python-for-loops-with-index-mastering-the-enumerate-function-1eim
Python for Loops with Index: Mastering the enumerate() Function - DEV Community
January 30, 2026 - The most recommended way to get both the index and the element in a loop is by using the built-in enumerate() function. It eliminates the need to track a counter manually or call len() on your list.
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-over-a-list-in-python
Iterate Over a List in Python - GeeksforGeeks
... Explanation: loop starts from index 0, prints the element at the current index, increments the index, and continues until all elements have been processed. range() function can be combined with a for loop to iterate through the indices of a list.
Published: July 16, 2026
🌐
W3Schools
w3schools.com › python › python_lists_loop.asp
Python - Loop Lists
Print all items, using a while loop to go through all the index numbers · thislist = ["apple", "banana", "cherry"] i = 0 while i < len(thislist): print(thislist[i]) i = i + 1 Try it Yourself » · Learn more about while loops in our Python While Loops Chapter.
🌐
Codefinity
codefinity.com › courses › v2 › 2f60173b-9829-4c84-8548-85bf65183f71 › 1593666f-8538-4286-9109-a352d6d9b604 › a9b50a1d-5137-49d1-8f7e-b4fbfd7deb48
Learn Iterating Over Indexes | Loops
This method ensures that the original ... on each item’s index in the list. ... Loop through the list using indices (use range(len(prices)))....
🌐
NumPy
numpy.org › devdocs › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.6.dev0 Manual
With this looping construct, the current value is accessible by indexing into the iterator. Other properties, such as tracked indices remain as before.
🌐
GeeksforGeeks
geeksforgeeks.org › python › access-the-index-and-value-using-python-for-loop
Access the Index and Value using Python 'For' Loop - GeeksforGeeks
July 23, 2025 - We can also use count from itertools along with zip() to achieve a similar effect. In this example, we have used itertools to access the index value in a for loop.
🌐
Real Python
realpython.com › python-for-loop
Python for Loops: The Pythonic Way – Real Python
3 weeks ago - To repeat code a number of times without processing the data of an iterable, use the for _ in range(times): construct. To do index-based iteration, you can use for index, value in enumerate(iterable): to access both index and item.