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 › python_lists_loop.asp
Python - Loop Lists
Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.
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
python - Loop through list with both content and index - Stack Overflow
It is very common for me to loop through a python list to get both the contents and their indexes. What I usually do is the following: S = [1,30,20,30,2] # My list for s, i in zip(S, range(len(S))): # Do stuff with the content s and the index i More on stackoverflow.com
🌐 stackoverflow.com
When using for loops are we iterating through the index or the actual values?
A "pure" for loop requires an index because you're just executing the same piece of code for whatever the range of that index is. What you're probably looking for is a foreach loop, which is really just syntactic sugar over a for loop that allows you to specify iterating over every member of a collection without defining an index. In Python it's a little different than a lot of other languages as there's no explicit foreach keyword. You just define your loop like: for season in seasons: More on reddit.com
🌐 r/learnprogramming
14
0
March 8, 2023
Confusion about list iteration with start offset / slicing

If you really need an iterator that doesn't copy, you can do something like this:

class Slice():
    def __init__(self,list_,i):
        self.list_ = list_
        self.current = i
        self.size = len(list_)
    def __iter__(self):
        return self
    def next(self):
        if self.current >= self.size:
          raise StopIteration
        val = self.list_[self.current]
        self.current += 1
        return val
 
 # assume l is some list
 for elem in Slice(l,i):
     # do something
More on reddit.com
🌐 r/Python
7
0
January 3, 2013
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-over-a-list-in-python
Iterate over a list in Python - GeeksforGeeks
Here we are using a while loop to iterate through a list. We first need to find the length of list using len(), then start at index 0 and access each item by its index then incrementing the index by 1 after each iteration.
Published   December 27, 2025
🌐
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. ... fruits = ['apple', 'banana', 'cherry'] for index, fruit in enumerate(fruits): print(f"{index}: {fruit}") Explain Code · This code prints each fruit ...
🌐
Trey Hunner
treyhunner.com › 2016 › 04 › how-to-loop-with-indexes-in-python
How to loop with indexes in Python
April 25, 2016 - For example, let’s say we’re ... along with their numbers (based on list indexes). 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.
🌐
StrataScratch
stratascratch.com › blog › mastering-loop-iterations-python-for-loop-index-explained
Mastering Loop Iterations: Python For Loop Index Explained - StrataScratch
October 17, 2024 - Have you ever noticed how Python's for loops make handling sequences a breeze? They automatically assign each element—such as a row in your dataset—to a loop variable. You can then use this variable inside your loop for various operations on each element. Maybe you want to see how clients' ages vary. Let’s Loop through client data and print their ages. Here is the code. for index, row in client_data.iterrows(): print(f"Client ID: {row['client_id']}, Age: {row['client_age']}") if index == 4: # Limit to 5 rows break
Find elsewhere
🌐
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
Line 5: We create a for loop and, using the range(len(iterable)) function, we refer to respective index numbers of all the items present in the list and create an iteration over all the items. Line 6: We print all the items of the list.
🌐
Programiz
programiz.com › python-programming › examples › index-for-loop
Python Program to Access Index of a List Using for Loop
my_list = [21, 44, 35, 11] for index in range(len(my_list)): value = my_list[index] print(index, value) ... You can access the index even without using enumerate(). Using a for loop, iterate through the length of my_list.
🌐
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
🌐
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.
🌐
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[i] for i in range(len(data))] creates a list of values by index. The zip() function can combine two lists: one with indices and one with elements, allowing simultaneous iteration.
🌐
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

🌐
Python documentation
docs.python.org › 3 › tutorial › datastructures.html
5. Data Structures — Python 3.14.3 documentation
Tuples are immutable, and usually ... or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list. A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is ...
🌐
Stack Abuse
stackabuse.com › how-to-access-index-in-pythons-for-loop
How to Access Index in Python's for Loop
January 6, 2021 - 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 when we want to access both the values and the indices of a 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 the below example, the start=1 parameter is used in the enumerate function to start the index at 1. This way, the loop iterates over the elements in the list, and the index variable starts from 1 instead of 0. # Start loop indexing with non ...
🌐
LearnPython.com
learnpython.com › blog › python-list-loop
7 Ways to Loop Through a List in Python | LearnPython.com
Sometimes you want to know the index of the element you are accessing in the list. The enumerate() function will help you here; it adds a counter and returns it as something called an ‘enumerate object’. This object contains elements that can be unpacked using a simple Python for loop. Thus, an enumerate object reduces the overhead of keeping a count of the number of elements in a simple iteration...
🌐
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 - You'll explore the use of enumerate(), loop iteration with the range() function, and how to implement these in practical examples. Utilize enumerate() to get both the index and value of items in a list.
🌐
iO Flood
ioflood.com › blog › python-for-loop-with-index
Learn Python: For Loops With Index (With Examples)
June 7, 2024 - In this code block, we’re accessing each item in the fruits list by its index. When you’re using a for loop with an index in Python, you’re essentially combining these two concepts: you’re iterating over a sequence with a for loop, and you’re keeping track of the index of each item.