Skip to content

Python for loop index | Example code

  • by

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. The enumerate() function returns a tuple containing the index and the value of each element in the list

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

Comment if you have any doubts or suggestions on this Python for loop 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