Access the Index in Python 'for' Loops

Kontext Kontext 0 184 0.17 index 7/15/2022

Python for loop is commonly used to iterate through a list. Sometimes it might be useful to also utilize the index in the for loops. We can achieve this by using built-in enumerate function or via an variable.

Code snippets

Via enumerate function

numbers = [10,20,30]
for i, number in enumerate(numbers):
    print('index={},value={}'.format(i,number))

Results:

index=0,value=10 index=1,value=20 index=2,value=30

Via an variable

numbers = [10,20,30]
i = 0
for number in numbers:
    print('index={},value={}'.format(i,number))
    i = i + 1

Results are the same as the above one.

python

Join the Discussion

View or add your thoughts below

Comments