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
🌐
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.
Top answer
1 of 16
9260

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
1370

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)
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
September 30, 2022
How do I iterate through a list by index using a list for the index?
Hint: If you do for i in indices:, what are the values of i? More on reddit.com
🌐 r/learnpython
15
1
May 2, 2023
python - Iterate a list with indexes - Stack Overflow
I’m Jody, the Chief Product and Technology Officer at Stack Overflow. Let’s... 5672 How can I access the index value in a 'for' loop? -1 Create a dictionary with list index as keys and input data as values · 37 Which is the most efficient way to iterate through a list in python? More on stackoverflow.com
🌐 stackoverflow.com
How can I skip the first element of a for loop?

Read the first line outside of the loop and ignore it

import pexpect
import re
child=pexpect.spawn('ping 000.000.0.00')
child.readline()
for i in range(5):
    ping=child.readline()
    print ping
More on reddit.com
🌐 r/learnpython
23
12
May 27, 2016
🌐
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
🌐
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.
🌐
Python Examples
pythonexamples.org › python-iterate-over-list-with-index
Iterate over List using Index in Python
1__ initialize variable x, with ... of Python Examples, we learned how to iterate over the items of a list with access to index as well using enumerate() function, with the help of well detailed examples....
🌐
Vultr Docs
docs.vultr.com › python › built-in › enumerate
Python enumerate() - Iterate With Index | Vultr Docs
December 5, 2024 - Create a list of items. Use the enumerate() function to iterate through the list, obtaining both index and value.
Find elsewhere
🌐
Quora
quora.com › How-do-you-iterate-over-a-list-and-pull-element-indices-at-the-same-time
How to iterate over a list and pull element indices at the same time - Quora
Answer (1 of 8): Adding to the correct answer by User-12748610390850255192, there is an optional start argument to the enumerate function, which I find very helpful when I need to count from 1 or any other number instead of 0. [code]for index, value in enumerate(numbers, start=1): print 'The ...
🌐
LabEx
labex.io › tutorials › python-how-to-iterate-with-index-in-python-419446
How to iterate with index in Python | LabEx
def safe_index_access(data, index, default=None): try: return data[index] except IndexError: return default sample_list = [10, 20, 30] print(safe_index_access(sample_list, 5, "Not Found")) Indexed iteration enables sophisticated data manipulation · Combine indexing with functional programming techniques ... Mastering index iteration in Python empowers programmers to write more readable and efficient code.
🌐
LearnPython.com
learnpython.com › blog › python-list-loop
7 Ways to Loop Through a List in Python | LearnPython.com
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.
🌐
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....
🌐
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.
🌐
Programiz
programiz.com › python-programming › examples › index-for-loop
Python Program to Access Index of a List Using for Loop
You can give any name to these variables. 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)
🌐
Reddit
reddit.com › r/learnpython › how do i iterate through a list by index using a list for the index?
r/learnpython on Reddit: How do I iterate through a list by index using a list for the index?
May 2, 2023 -

I have a course assignment that's got me stumped. I am given two lists:

names = ["john", "jane", "joe"]
indices = [1, 2, 3]

I need to create a for loop to iterate through names by index, but somehow use indices for the indices. I cannot use enumerate().

Any ideas how this is done? Thank you!

🌐
AskPython
askpython.com › home › ways to iterate through list in python
Ways to Iterate Through List in Python - AskPython
January 16, 2024 - Python’s range() method can be used in combination with a for loop to traverse and iterate over a list in Python. The range() method basically returns a sequence of integers i.e. it builds/generates a sequence of integers from the provided start index up to the end index as specified in the argument list.
🌐
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 - Lists are one of the most commonly iterated sequence types in Python. The basic way to iterate through a list and access each element by index is with 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.
🌐
Educative
educative.io › answers › how-to-iterate-over-a-list-in-python
How to iterate over a list in Python
It returns tuples containing both the index and the corresponding value, simplifying the process of tracking positions: ... As we iterate through the list names, the enumerate function pairs up each name with its respective index, i.e., Alice ...
🌐
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.