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
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. List Comprehension offers the shortest syntax for looping through lists:
Discussions

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
Python For Loops Do Not Behave As Expected
For loops in Python are baffling to a VBA programmer. NumLst = [8, 1, 3, 2] for I in NumLst: print (I, end = ' ') Output from this is 8 1 3 2 Not what I expected. I thought was asking Python to print the loop counter, not the contents of the loop. I expected 0 1 2 3 Thought maybe `enumerate ... More on discuss.python.org
🌐 discuss.python.org
0
April 18, 2021
Adding an index to a list using a for loop
I think this would work for you. for index, person in enumerate(people): person.index = index It would likely end up better to add this index during the creation of the class instances. More on reddit.com
🌐 r/learnpython
7
1
August 16, 2022
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
🌐
StrataScratch
stratascratch.com › blog › mastering-loop-iterations-python-for-loop-index-explained
Mastering Loop Iterations: Python For Loop Index Explained - StrataScratch
October 17, 2024 - We iterate through the orders_data and modify rows based on the index if the order was canceled by the client. A new column, client_cancelled, is added and set to 1 for these orders. If you want to see more check these Python Interview Questions. When dealing with massive datasets, performance becomes crucial. While for loops with indexes give you control, they're not always the most efficient with big data.
🌐
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 ...
🌐
Trey Hunner
treyhunner.com › 2016 › 04 › how-to-loop-with-indexes-in-python
How to loop with indexes in Python
This first creates a range corresponding to the indexes in our list (0 to len(colors) - 1). 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.
🌐
Python Engineer
python-engineer.com › posts › access-index-in-for-loop
How to access the index in a for loop in Python - Python Engineer
my_list = ["apple", "banana", "cherry"] for index, item in enumerate(my_list, start=1): print(index, item) ... As an alternative you could also iterate over the indices using range(len(your_list)). This works too, however, the first option using ...
🌐
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: ...
Find elsewhere
🌐
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

🌐
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 - Python programming language supports the different types of loops, the loops can be executed in different ways. 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;)
🌐
Mimo
mimo.org › glossary › python › for-loop
Python For Loop: Syntax and Examples [Python Tutorial]
range() is a built-in function that creates a list of numbers starting at 0 and stopping before a specified integer. This makes the range function ideal for creating Python for loops with index variables.
🌐
The New Stack
thenewstack.io › home › python indexing vs. for loops: what’s really faster?
Python Indexing vs. For Loops: What’s Really Faster? - The New Stack
July 10, 2025 - Looping with indexing is a way to iterate through a sequence (like a list, tuple or string) by looping over its indexes, then using those indexes to access each element. This method combines the structure of a for loop with the precision of ...
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.3 documentation
(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.) One way to think of the else clause is to imagine it paired with the if inside the loop. As the loop executes, it will run a sequence like if/if/if/else.
🌐
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.
🌐
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() ...
🌐
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.
🌐
Python.org
discuss.python.org › python help
Python For Loops Do Not Behave As Expected - Python Help - Discussions on Python.org
April 18, 2021 - For loops in Python are baffling to a VBA programmer. NumLst = [8, 1, 3, 2] for I in NumLst: print (I, end = ' ') Output from this is 8 1 3 2 Not what I expected. I thought was asking Python to print the loop counter, not the contents of the loop. I expected 0 1 2 3 Thought maybe `enumerate ...
🌐
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}')
🌐
Reddit
reddit.com › r/learnpython › adding an index to a list using a for loop
r/learnpython on Reddit: Adding an index to a list using a for loop
August 16, 2022 -

Hello,

I have a class that instantiates an object with a number of attributes. I have a list that contains an ordered number of instances of that class. I would like to add to each of those instantiations an index of their place and I thought I should be able to do that with a for loop, but I'm missing something.

Thank you very much for taking a look at this!

Here is my code:

class Dude:
  def __init__(self, name, cash):
    self.name = name
    self.cash = float(cash)
  
  def __str__(self):
    return "{} has {} in cash.".format(self.name, self.cash)

Bob = Dude('Bob', 20)
James = Dude('James', 30)
Carl = Dude('Carl', 40)
Debbie = Dude('Debbie', 5)

people = [Bob, James, Carl, Debbie]

#Here's where the problem is

for i in people:
  print(i.name)#this works

for i in people:
  i.index = 0 #this works, it creates an attribute in each class instance that has a value of 0.

for i in people:
  i.index = i #this does not work
🌐
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.