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
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)
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_iterating.asp
NumPy Array Iterating
Iterating means going through elements one by one. As we deal with multi-dimensional arrays in numpy, we can do this using basic for loop of python.
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
October 5, 2022
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
Iterate over indices and values of array

The correct answer is to use pairs:

for (i, v) in pairs(A)
    println(i, v)
end

enumerate does not return indices, and can cause bugs for some array types. It should therefore be avoided for this use.

More on reddit.com
🌐 r/Julia
10
15
August 19, 2020
[Python] How can you increment a list index using a for / while loop in Python?
i = 0 while len(list) < rankCount: for roster_member in response["rankings"][i]["run"]["roster"]: // do something i+=1 Would something like this work for you? More on reddit.com
🌐 r/learnprogramming
4
1
October 31, 2017
🌐
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.
🌐
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.
🌐
Programiz
programiz.com › python-programming › examples › index-for-loop
Python Program to Access Index of a List Using for Loop
You can access the index even without using enumerate(). Using a for loop, iterate through the length of my_list.
🌐
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.
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.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python iterate over an array
Python Iterate Over an Array - Spark By {Examples}
May 31, 2024 - Let’s also see how to iterate ... the np.ndenumerate() function. For example, # Iterate 2-D array and get indexes & values for index, value in np.ndenumerate(arr): print(index, value) Yields below output. # Output: (0,) 0 (1,) 1 (2,) 2 (3,) 3 (4,) 4 (5,) 5 (6,) 6 (7,) 7 (8,) 8 (9,) 9 (10,) 10 (11,) 11 · Sometimes you may need to loop through single-dimension of 2-D NumPy array, We can use nditer() function with 'flags' ...
🌐
NumPy
numpy.org › devdocs › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.5.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.
🌐
NumPy
numpy.org › doc › stable › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.4 Manual
The iterator object nditer, introduced ... This page introduces some basic ways to use the object for computations on arrays in Python, then concludes with how one can accelerate the inner loop in Cython....
🌐
Python Guides
pythonguides.com › python-for-loop-index
How to Use Python For Loop with Index
October 14, 2025 - While this approach works fine, it’s not as efficient or elegant as enumerate() or range(). I’d recommend using it only when you need to manipulate the index dynamically during iteration. If you’re working with NumPy arrays, you can use the built-in ndenumerate() function to loop through ...
🌐
Llego
llego.dev › home › blog › accessing elements by index during iteration in python
Accessing Elements by Index During Iteration in Python - llego.dev
May 25, 2023 - zip() pairs up elements from each sequence by index into tuples. Any number of iterables can be zipped together. This is handy any time you need to loop over multiple related sequences in sync. NumPy provides fast multi-dimensional array data structures for numerical Python programming.
🌐
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 - The for loop then iterates over these pairs, and you can use the index variable to access the index of the current element. # Using enumerate() to access both index & item courses = ['java','python','pandas','sparks'] print("Get both index & ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-over-a-list-in-python
Iterate over a list in Python - GeeksforGeeks
a = [1, 3, 5, 7, 9] # Here, i and val reprsents index and value respectively for i, val in enumerate(a): print (i, val) ... List comprehension is similar to for loop. It provides the shortest syntax for looping through list.
Published   December 27, 2025
🌐
NumPy
numpy.org › doc › 2.1 › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.1 Manual
Those who want really good performance out of their low level operations should strongly consider directly using the iteration API provided in C, but for those who are not comfortable with C or C++, Cython is a good middle ground with reasonable performance tradeoffs. For the nditer object, this means letting the iterator take care of broadcasting, dtype conversion, and buffering, while giving the inner loop to Cython. For our example, we’ll create a sum of squares function. To start, let’s implement this function in straightforward Python.
🌐
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 ...
🌐
NumPy
numpy.org › doc › 2.2 › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.2 Manual
November 21, 2025 - Those who want really good performance out of their low level operations should strongly consider directly using the iteration API provided in C, but for those who are not comfortable with C or C++, Cython is a good middle ground with reasonable performance tradeoffs. For the nditer object, this means letting the iterator take care of broadcasting, dtype conversion, and buffering, while giving the inner loop to Cython. For our example, we’ll create a sum of squares function. To start, let’s implement this function in straightforward Python.
🌐
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 ...
🌐
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.