Python for loop index | Example code

Using the range() function or enumerate() function will allow us to iterate over a list and retrieve both the index and the value of each item in the Python list.

Example get index and value using for loop in Python

Simple example code loop over lists items with indexes.

Using enumerate

Use the enumerate() function to generate the index along with the elements of the sequence you are looping over:

items = ["a", "b", "c"]

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

Output:

Python for loop index

Using range()

use range(len(our_list)) and then look up the index like before:

presidents = ["ABC", "XYZ", "PQR"]

for i in range(len(presidents)):
    print("President {}: {}".format(i + 1, presidents[i]))

Output:

President 1: ABC
President 2: XYZ
President 3: PQR

Do comment if you have any doubts and suggestions on this Python for loop topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.