Skip to content

Python iterate list with index | Example code

  • by

Use the built-in function enumerate() to access the index in a for loop while iterating a list in Python.

for idx, val in enumerate(ints):
    print(idx, val)

Note: Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic. Check out PEP 279 for more.

Example iterate list with index in Python

Simple example code gets the index with the element as you iterate:

ints = [55, 44, 33, 22, 11]

for idx, val in enumerate(ints):
    print(idx, val)

Output:

Python iterate list with index

Another example iterates through indexes of the list of string

items = ['Cricket', 'Chess', 'football']

for index, item in enumerate(items):
    print(index, item)

Output:

0 Cricket
1 Chess
2 football

Another way

Using for loop with index.

Note: Python indexes start at zero.

colors = ["red", "green", "blue", "purple"]

for i in range(len(colors)):
    print(i, colors[i])

Output:

0 red
1 green
2 blue
3 purple

Do comment if you have any doubts or suggestions on this Python iteration topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading