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.
🌐
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 3, 2022
python - loop through array or list in variable steps - Stack Overflow
I'm trying to figure out how to loop through an array or list in variable steps. So for example, if I have the following list... a = [0,0,1,0,0,1,0] ...and want to use the following logic: Star... More on stackoverflow.com
🌐 stackoverflow.com
May 31, 2024
Loop over an an array of array
I have an array of arrays I want to loop over to return two arrays called hills and valleys. When looping through each element, we check the item at index 1 that is element[0] if the value is equal to zero, we create another array and push the value inside. we keep a trace of it still when ... More on discuss.python.org
🌐 discuss.python.org
0
0
November 28, 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
Top answer
1 of 16
9258

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 › 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.
🌐
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.
🌐
NumPy
numpy.org › doc › stable › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.4 Manual
With this looping construct, the current value is accessible by indexing into the iterator. Other properties, such as tracked indices remain as before.
Find elsewhere
🌐
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' ...
🌐
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
🌐
W3Schools
w3schools.com › python › gloss_python_array_loop.asp
Python Loop Through an Array
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... You can use the for in loop to loop through ...
🌐
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.
🌐
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.
🌐
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.1 › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.1 Manual
October 14, 2025 - 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 › 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.
🌐
Python Guides
pythonguides.com › python-for-loop-index
How to Use Python For Loop with Index
1 month ago - 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 ...
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 402440 › looping-through-a-list-starting-at-index-2
python - Looping through a list starting at index ... [SOLVED] | DaniWeb
December 22, 2011 - Note, indexing in Python starts at 0 - so to start at index 2 will actually … — Member #912166 Jump to Post ... This'll iterate through the items in lines starting at index 2 ending at index len(lines) - 1.
Top answer
1 of 3
3

Don't use a for loop.

for loops in python are different than in C or Java. In those languages, a for loop has an initial condition, a termination condition, and an increment for each time the loop runs. Whereas in python, a for loop is more of a for each loop - you give it an iterable object, and it runs the code for every item in that iterable object.

Modifying the iterable object while you're running through it is a bad idea that can have difficult-to-predict repercussions and will usually break your code.


However, you can always use a while loop:

a = [0,0,1,0,0,1,0]
idx = 0

while(idx < len(a) - 2):
    print(idx)
    if a[idx + 2] == 0:
        idx += 2
    elif a[idx + 2] == 1:
        idx += 1
print(idx)

which produces the expected output

0 1 3 4 6

Or, if you change the increments to 3 and 2 respectively, rather than 2 and 1,

0 2 5
2 of 3
0

Your reasoning is pretty confusing, and I don't see ANY application for this, but here is how I understand your problem...

The reason is because you aren't actually returning the values, you're simply returning the index + 3, which is wrong to begin with. What you're trying to do is point to a new index of the array based on its value and return the index if it contains a value greater than 0.

You need to reference the index you want, check its value, then return the index which contains a value.

a = [0, 0, 1, 0, 0, 1, 0]
for i, v in enumerate(a):
   if i == 0:
      print(i)
      next
   if v == 0:
      next
   else
      print(i)

But let's be honest, this is extremely ugly and un-pythonic. Let's simply check for whether a[i] contains a value, and if so, return the index...

for i, v in enumerate(a):
   if v or i == 0:
      print(i)

The purpose of if v or i == 0 is to check if v has a value, if so, print the index. OR if we are looking at the first element of i.

If you want to EXPLICITLY move the index by two, you must set your index at the start and use a while loop, since enumerate can't help you here and doesn't actually let you move the indicies...

a = [0, 0, 1, 0, 0, 1, 0]
i = 0
while i < len(a) - 1:   # -1 to avoid out of bounds error
   print(i)
   if a[i + 2] == 0:
      i += 2
   elif a[i + 2] == 1:
      i += 1
print(i)            # Final print statement for the last index at the end of the while loop

I want to impress upon you the fact that this solution does NOT scale with different or larger lists, which is why it isn't recommended. By simply checking for whether a value does or doesn't exist, you guarantee your accuracy.

You should simply return the index based upon whether or not it contains a value. Even for very large lists, this will be extremely fast, and will always scale, even for values greater than 1.

The only other reason I would see you would want to do this differently is if you're doing string-search algorithms.

🌐
Python.org
discuss.python.org › python help
Loop over an an array of array - Python Help - Discussions on Python.org
November 28, 2023 - When looping through each element, we check the item at index 1 that is element[0] if the value is equal to zero, we create another array and push the value inside. we keep a trace of it still when ...
🌐
TutorialsPoint
tutorialspoint.com › python-program-to-iterate-over-an-array
Python Program to Iterate Over an Array
May 15, 2023 - Note: The while loop will become ... value is 0. In this example we will display the element along with the corresponding index value using the enumerate() function....