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 - 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.
🌐
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

🌐
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 ...
🌐
StrataScratch
stratascratch.com › blog › mastering-loop-iterations-python-for-loop-index-explained
Mastering Loop Iterations: Python For Loop Index Explained - StrataScratch
October 17, 2024 - 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.
🌐
Python Morsels
pythonmorsels.com › looping-with-indexes
Looping with indexes - Python Morsels
October 8, 2020 - Often when you're trying to loop with indexes in Python, you'll find that you actually care about counting upward as you're looping, not actual indexes. Let's say we have a variable, favorite_fruits that points to a list of strings: >>> favorite_fruits = ["jujube", "pear", "watermelon", "apple", "blueberry"] ... >>> n = 1 >>> for fruit in favorite_fruits: ... print(n, fruit) ... n += 1 ... 1 jujube 2 pear 3 watermelon 4 apple 5 blueberry · We're printing out n and fruit (which represents each of our fruits).
🌐
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.
🌐
iO Flood
ioflood.com › blog › python-for-loop-with-index
Learn Python: For Loops With Index (With Examples)
June 7, 2024 - Let’s dive in and explore the power of ‘for loops with index’ in Python. You can use the enumerate() function in a for loop to get both the index and the value.
Find elsewhere
🌐
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 - When iterating over a range of numbers in a for loop in Python, you can use the enumerate function to access both the index and the value at that index.
🌐
Trey Hunner
treyhunner.com › 2016 › 04 › how-to-loop-with-indexes-in-python
How to loop with indexes in Python
We could use range(len(our_list)) and then lookup the index like before: But there’s a more idiomatic way to accomplish this task: use the enumerate function. Python’s built-in enumerate function allows us to loop over a list and retrieve ...
🌐
Vultr
docs.vultr.com › python › examples › access-index-of-a-list-using-for-loop
Python Program to Access Index of a List Using for Loop | Vultr Docs
November 25, 2024 - ... fruits = ['apple', 'banana', ... fruit name for each element in the fruits list. enumerate() provides a convenient way to access both the index and the value during a loop....
🌐
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
So rather than saying “do this n times”, a foreach loop essentially says “do this to everything in the sequence”. For scenarios where we actually need the index or counter variable, we can use Python’s built-in enumerate function. The enumerate function returns an iterable. Each element of this iterable is a tuple containing the index of the item and the original item value, like so:
🌐
PythonHow
pythonhow.com › how › accesses-the-index-in-for-loops
Here is how to accesses the index in for loops in Python
colors = ['red', 'green', 'blue'] # Loop over the elements in the list and print their index and value for i, color in enumerate(colors): print(f'{i}: {color}') ... To access the index of an element in a list or other iterable object in a for loop in Python, you can use the enumerate() function.
🌐
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 ...
🌐
Toppr
toppr.com › guides › python-guide › examples › python-examples › native-datatypes › index-for-loop › python-program-to-access-index-of-a-list-using-for-loop
Python Program to Access Index of a List Using for Loop: Examples
October 11, 2021 - We access the list on that index with each increase. This can be accomplished by combining range() and len() as shown below. ... my_list = ['Zero', 'One', 'Two', 'Three', 'Four'] print ('Indices and values in the list:') for i in range(len(my_list)): val = my_list[i] print((i, val)) ... Another ...
🌐
Medium
medium.com › @python-javascript-php-html-css › how-to-use-an-index-value-in-a-python-loop-a-guide-38396427efcb
How to Use an Index Value in a Python Loop: A Guide
September 17, 2024 - ... Another method to access index values in a for loop is by using the zip() function. By combining range() and the sequence, you can iterate over both the index and the items simultaneously.
🌐
Stack Abuse
stackabuse.com › how-to-access-index-in-pythons-for-loop
How to Access Index in Python's for Loop
January 6, 2021 - In this article, we will go over different approaches on how to access an index in Python's for loop. The easiest, and most popular method to access the index of elements in a for loop is to go through the list's length, increasing the index. On each increase, we access the list on that index: ...
🌐
Python Guides
pythonguides.com › python-for-loop-index
How to Use Python For Loop with Index
October 14, 2025 - Learn how to use the Python for loop with index using five easy methods. Includes examples with enumerate(), range(), zip(), and NumPy for real-world coding.
🌐
Better Stack
betterstack.com › community › questions › how-to-access-index-in-for-loops-in-python
How to access the index in for loops in Python? | Better Stack Community
In python, if you are enumerating over a list using the for loop, you can access the index of the current value by using enumerate function. ... Simply wrap the list you want to iterate over using the enumerate function and you can access not ...
🌐
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.