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

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
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
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
Iterating through a numpy array
A quick note to start: In numpy, the row index comes before the column index, so, for example, a 3x2 array would have the form [[1,2],[3,4],[5,6]]. In any case, for an nx2 array called arr you can iterate through the pairs (rows) as you would through elements of a regular sequence: for n in arr: n # is your pair For a 2xn array, you can use for i in xrange(arr.shape[1]): arr[:, i] # is your pair but there are a number of ways to do this second form. Here 's a stackoverflow entry that treats this question in more detail. Worth mentioning: In general, if you can avoid iterating over a numpy array, you should. The iteration sacrifices some of the performance improvements over regular python given by the C-implemented numpy arrays. Numpy (and scipy) have a large selection of functions that allow you to avoid iteration (especially by leveraging the axis keyword to perform some computation over a specific axis) -- so search through the docs a bit before committing to this route. (an example of what I mean: to obtain the mean value of each of your tuples, use np.mean(arr, axis=1) in the nx2 case or axis=0 in the 2xn case to get an n-lengthed sequence of the mean of each pair; there are many functions like this) More on reddit.com
🌐 r/learnpython
7
2
November 14, 2014
🌐
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.
🌐
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.
🌐
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.
🌐
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
🌐
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.
🌐
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
🌐
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.
🌐
Stack Abuse
stackabuse.com › how-to-access-index-in-pythons-for-loop
How to Access Index in Python's for Loop
January 6, 2021 - Here, we don't iterate through the list, like we'd usually do. We iterate from 0..len(my_list) with the index. Then, we use this index variable to access the elements of the list in order of 0..n, where n is the end of the list. ... enumerate() is a built-in Python function which is very useful ...
🌐
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.
🌐
YouTube
youtube.com › watch
How to loop with indexes in Python | Loop through list with both content and index | Python Basics - YouTube
Disclaimer:It doesn't feel good to have a disclaimer in every video but this is how the world is right now. All videos are for educational purpose and use th...
Published: December 4, 2019
🌐
YouTube
youtube.com › case digital
How To Iterate Through A List With Index In Python - YouTube
In this python tutorial, I answer the question of how to iterate through a list with index in python! If fact I'll show you two different ways you can iterat...
Published: January 13, 2023
Views: 876
🌐
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 ...
🌐
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
🌐
Educative
educative.io › answers › how-to-loop-through-a-list-using-the-index-numbers-in-python
How to loop through a list using the index numbers in Python
The combination of the range() and len() functions, (range(len(iterable), is used to iterate over a list in Python. Using the two functions together, we can refer to the index numbers of all items or elements in a list.
🌐
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.