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
I often see new Python programmers attempt to recreate traditional for loops in a slightly more creative fashion in Python: This first creates a range corresponding to the indexes in our list (0 to len(colors) - 1).
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_lists_loop.asp
Python - Loop Lists
Learn more about for loops in our Python For Loops Chapter. You can also loop through the list items by referring to their index number. Use the range() and len() functions to create a suitable iterable.
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)
๐ŸŒ
StrataScratch
stratascratch.com โ€บ blog โ€บ mastering-loop-iterations-python-for-loop-index-explained
Mastering Loop Iterations: Python For Loop Index Explained - StrataScratch
October 17, 2024 - Letโ€™s look at how to use the for-loop index with the client data dataset. You can easily access indices in your loops by using range() and len().
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-range-function-explained-with-code-examples
Python range() Function โ€“ Explained with Code Examples
October 6, 2021 - This is when the optional step argument comes in handy. The general syntax is shown below: ... When you use this syntax and loop through the range object, you can go from start to stop-1 with strides of size step.
๐ŸŒ
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.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ when using for loops are we iterating through the index or the actual values?
r/learnprogramming on Reddit: When using for loops are we iterating through the index or the actual values?
March 8, 2023 -
for i in range(10,20):
    print(i)

I understand that i is going through the values 10 to 20. I know there can be an index attached but why do we have to explicitly associate an index to a value to change the value we want?

seasons = ['fall','winter','spring','summer'] # works like the enurate function
    for i in range(len(seasons)):
        if seasons[i] == 'summer':
            seasons[i] = 'New season'
        print(i , seasons[i])

Why do we have to associate the index to change the actual value? What exactly are we looping through

Find elsewhere
๐ŸŒ
Real Python
realpython.com โ€บ python-for-loop
Python for Loops: The Pythonic Way โ€“ Real Python
3 weeks ago - Pythonโ€™s for loop iterates over items in a data collection, allowing you to execute code for each item. To iterate from 0 to 10, you use the for index in range(11): construct.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Python for Loop (With range, enumerate, zip) | note.nkmk.me
August 18, 2023 - You can use the range() function to create a counter (index) for a for loop. ... In Python 3, range() creates a range object, and its content is not displayed when printed with print(). For explanation purposes, the following example uses list() ...
๐ŸŒ
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 - In this article, you have learned to access iterable objects with the index in the for loop by using range(), enumerate() and zip(). You have also learned the basic idea of list comprehension, using this how we can access the index with corresponding items.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ looping-with-indexes
Looping with indexes - Python Morsels
October 8, 2020 - We start n at 1 and we're incrementing it by 1 in each iteration of our loop. Instead of keeping track of counter ourselves, how about thinking in terms of indices and using range(len(favorite_fruits)) to grab each of the indexes of all the items in this list: >>> favorite_fruits = ["jujube", "pear", "watermelon", "apple", "blueberry"] >>> >>> for i in range(len(favorite_fruits)): ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_for_loops.asp
Python For Loops
This is less like the for keyword ... statements, once for each item in a list, tuple, set etc. ... The for loop does not require an indexing variable to set beforehand....
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ how to start python for loop at 1
How to Start Python For Loop at 1 - Spark By {Examples}
May 31, 2024 - If you want to use slicing to start ... of 0? To start a Python for loop at 1 instead of 0, you can use the range function and specify a starting value of 1....
๐ŸŒ
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", ... element) ... range() function returns an iterable with range of numbers. So, range() function can be used to iterate over the range of indexes of the iterable....
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-range.html
Python range() Function
The most common form is range(n), given integer n returns a numeric series starting with 0 and extending up to but not including n, e.g. range(6) returns 0, 1, 2, 3, 4, 5. With Python's zero-based indexing, the contents of a string length 6, are at index numbers 0..5, so range(6) will produce ...
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ examples โ€บ index-for-loop
Python Program to Access Index of a List Using for Loop
Print the required variables inside the for loop block. The function of enumerate() is to add a counter (i.e. index) to the iterate and return it. my_list = [21, 44, 35, 11] for index, val in enumerate(my_list, start=1): print(index, val) ... The value of the parameter start provides the starting ...
๐ŸŒ
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 - In this method, we are using enumerate() in for loops to get the index value over the given range. ... # Method 2: Using enumerate fruits = ['apple', 'banana', 'orange'] print(&quot;Indices and values in list:&quot;) # Use enumerate to get both ...
๐ŸŒ
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 - In this example, the for loop executes the statement print(index) exactly five times. If you want to show 5 numbers from 1 to 5 on the screen, you can do something like this: for index in range(5): print(index + 1)Code language: Python (python)