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)
๐ŸŒ
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 - Below are some of the examples by which we can access the index value in Python: ... In this method, we are using the range() function to generate indices and access values in a list by their position. ... # create a list of fruits fruits = ['apple', 'banana', 'orange'] print(&quot;Indices and Index value :&quot;) # Iterate over the indices of the list and access elements using indices for i in range(len(fruits)): print(f&quot;Index: {i}, Value: {fruits[i]}&quot;)
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ built-in โ€บ enumerate
Python enumerate() - Iterate With Index | Vultr Docs
December 5, 2024 - Use the enumerate() function to iterate through the list, obtaining both index and value.
๐ŸŒ
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

๐ŸŒ
StrataScratch
stratascratch.com โ€บ blog โ€บ mastering-loop-iterations-python-for-loop-index-explained
Mastering Loop Iterations: Python For Loop Index Explained - StrataScratch
October 17, 2024 - This loop prints the clientโ€™s ID and age for the first five rows in the client_data.csv dataset. By using break, we control how much data is shown. The for loop index refers to the position of the current element in the sequence during each iteration of a for loop. Sometimes, you may want to access the index along with the value of each component while iterating.
๐ŸŒ
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. Loop variable index starts from 0 in this case. In each iteration, get the value of the list at the current index using the statement value = my_list[index]. Print the value and index.
Find elsewhere
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ looping-with-indexes
Looping with indexes - Python Morsels
October 8, 2020 - Each tuple has a number (counting upward) and the next item from our favorite_fruits iterable. We could index this tuple, using item[0] and item[1], to grab these two values:
๐ŸŒ
Trey Hunner
treyhunner.com โ€บ 2016 โ€บ 04 โ€บ how-to-loop-with-indexes-in-python
How to loop with indexes in Python
Pythonโ€™s built-in enumerate function ... each item in the list: The enumerate function gives us an iterable where each element is a tuple that contains the index of the item and the original item value....
๐ŸŒ
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. ... a = [1, 3, 5, 7, 9] # On each iteration val is passed to print function # And printed in the console.
Published ย  December 27, 2025
๐ŸŒ
Real Python
realpython.com โ€บ python-enumerate
Python enumerate(): Simplify Loops That Need Counters โ€“ Real Python
June 23, 2025 - Pythonโ€™s enumerate() function helps you with loops that require a counter by adding an index to each item in an iterable. This is particularly useful when you need both the index and value while iterating, such as listing items with their positions.
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-for-loop-with-index
Learn Python: For Loops With Index (With Examples)
June 7, 2024 - In Python, a for loop is used to iterate over a sequence such as a list, tuple, dictionary, string, etc. Itโ€™s a control flow statement, which allows code to be executed repeatedly.
๐ŸŒ
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 - Provides concise and readable code by avoiding manual indexing inside loops. Overall, enumerate() should be your preferred approach when you need both the index and value during iteration.
๐ŸŒ
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
๐ŸŒ
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 - You can use the enumerate() function in a for loop to access both the elements and their corresponding indices. For example, the enumerate() function is used in the for loop to iterate over both the indices and values of the courses.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ accessing the index in a `for` loop in python
Accessing the Index in a `for` Loop in Python | Sentry
Letโ€™s say we want to print the ... of start to 1, like so: directions = ['north', 'east', 'south', 'west'] for index, direction in enumerate(directions, start=1): print(f"{index} {direction}") ... There are other ways of ...
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-for-loop-index
How to Use Python For Loop with Index
October 14, 2025 - Using wrong start index: Remember that Python uses zero-based indexing. If you want a human-readable index, start from 1 using enumerate(states, start=1). Forgetting tuple unpacking: When using enumerate(), make sure to unpack both the index and the item correctly:
๐ŸŒ
Enterprise DNA
blog.enterprisedna.co โ€บ python-for-loop-index
Python for Loop Index: How to Access It (5 Easy Ways) โ€“ Master Data Skills + AI
Experimenting with these methods and understanding their nuances will not only enhance your coding skills but also allow you to write more Pythonic code. Happy coding! To use enumerate() in a for loop, you pass the list or sequence you want to iterate over as an argument to the function. The ...