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
๐ŸŒ
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 ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_lists_loop.asp
Python - Loop Lists
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... 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.
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)
๐ŸŒ
Trey Hunner
treyhunner.com โ€บ 2016 โ€บ 04 โ€บ how-to-loop-with-indexes-in-python
How to loop with indexes in Python
For example, letโ€™s say weโ€™re printing out president names 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. Pythonโ€™s built-in enumerate function allows us to loop ...
๐ŸŒ
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.
๐ŸŒ
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 Python provides a simpler method of looping where instead of retrieving item indexes and looking up each element, we can just loop over the elements directly, like so: directions = ['north', 'east', 'south', 'west'] for direction in directions: ...
๐ŸŒ
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.
๐ŸŒ
StrataScratch
stratascratch.com โ€บ blog โ€บ mastering-loop-iterations-python-for-loop-index-explained
Mastering Loop Iterations: Python For Loop Index Explained - StrataScratch
October 17, 2024 - Python's for loops are user-friendly but can drag with large datasets. Alternatives like vectorized operations in pandas often run faster. Using iloc[] or at[] inside loops can be costly because pandas shine with vectorized tasks, not explicit looping. If you must use it for loops, try enumerate(). It automatically tracks the index as you iterate, cutting out manual handling.
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 - 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 ...
๐ŸŒ
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', 'cherry'] for i in range(len(fruits)): print(f"Index: {i}, Fruit: {fruits[i]}") Explain Code ยท Here, range(len(fruits)) creates a sequence of indices from 0 to the length of the list minus one.
๐ŸŒ
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

๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-for-loop-with-index
Learn Python: For Loops With Index (With Examples)
June 7, 2024 - In this example, we use the enumerate() function in a for loop to iterate over a list of fruits. The enumerate() function adds a counter to the list (or any other iterable), and returns it in a form of enumerate object.
๐ŸŒ
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}')
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-for-loop-index
How to Use Python For Loop with Index
October 14, 2025 - Modifying the list while looping: Avoid changing the list (adding or removing elements) inside the for loop. It can cause unexpected behavior or index errors. 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: ... Letโ€™s say you have a list of states and their populations, and you want to print them in a formatted way with their index.
๐ŸŒ
Real Python
realpython.com โ€บ python-enumerate
Python enumerate(): Simplify Loops That Need Counters โ€“ Real Python
June 23, 2025 - Calling enumerate() allows you to control the flow of a loop based on the index of each item in a list, even if the values themselves arenโ€™t important to your logic. You can also combine mathematical operations with conditions for the index. For example, you might need to grab every second item from a Python ...
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ looping-with-indexes
Looping with indexes - Python Morsels
October 8, 2020 - 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: ...
๐ŸŒ
Enterprise DNA
blog.enterprisedna.co โ€บ python-for-loop-index
Python for Loop Index: How to Access It (5 Easy Ways) โ€“ Master Data Skills + AI
To access the index of elements in Python while iterating through them in a โ€˜forโ€™ loop, you can use the enumerate() function. enumerate() returns both the index and the item from the iterable. This way, within the loop, you have access to both the index of the current item and the item ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ using python list index in a for loop
r/learnpython on Reddit: Using python list index in a for loop
January 4, 2024 -

I have a predefined list of 0s and 2s, e. g. discr_breaklist= [0, 0, 2, 2, 0, 2, 2], further "discr" And what I want to do is write a for loop which creates a new list, c_breaklist, further "c". That list:

  • has a length 1 greater than the old list, because 0 is added as the first value by default

  • the second value of c is discr_breaklist[0]

  • to create c, I then iterate over discr_breaklist for range(1, len(discr_breaklist)), since discr_brealist[0] has already been added unaltered

  • if a given item in discr is 0, then 0 should be added to c_breaklist

  • if a given value of discr is 2, then that value should be added to the value immediately preceding it, and the cumulative value added to c_breaklist. If several 2s follow each other in discr, then they get cumulated and added to c with each iteration of the loop.

It's hard to put into words, here's my two lists:

discr_breaklist = [0, 0, 2, 2, 0, 2, 2] c_breaklist = [0, 0, 0, 2, 4, 0, 2, 4]

This is my code thus far:

c_breaklist = [0, discr_breaklist[0]]
    for m in range(1, len(discr_breaklist)):
        if discr_breaklist[m] == 0:
            cumulative = 0
            c_breaklist.append(cumulative)
        else:
            cumulative = discr_breaklist[m]
            cumulative += c_breaklist[the value of c_breaklist immediately preceeding m]
            c_breaklist.append(cumulative)
    print(c_breaklist)
    return c_breaklist

Don't know how to write this. I've tried for so long to solve this...

If anybody can be of help, I'd be very grateful. Thanks!

๐ŸŒ
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 - Letโ€™s alter it such that it starts at 2. ... my_list = ['Zero', 'One', 'Two', 'Three', 'Four'] print ('Indices and values in the list:') for index, val in enumerate(my_list, start = 2): print((index, val)) ... The most straightforward and often used approach for accessing the index of elements ...