How to access the index in a for-loop

--

When looping through a list:

items = [10, 20, 30, 40, 50, 60]
for item in items:
print(item)

You get:

10
20
30
40
50
60

This is fine, but what is you want to print:

Item 1 is 10
Item 2 is 20
Item 3 is 30
Item 4 is 40
Item 5 is 50
Item 6 is 60

How can you access the index in a for loop?

This can be done using the enumerate() built-in function which is available in Python2 and Python3.

for index, item in enumerate(items, start=1):
print(f'Item {index} is {item}')

Python’s indexes start at zero, so you would get 0 to 5 when iterating through the index values. If you want the count to start at 1 and end at 6, add start=1 in the enumerate() function.

--

--

Adriaan van Niekerk
Adriaan van Niekerk

Written by Adriaan van Niekerk

A Mechanical Engineer who loves to program and teach others the joys of being an engineer

No responses yet