Access the Index in Python 'for' Loops

visibility 20 access_time 6 days ago languageEnglish
more_vert

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.

info Last modified by Kontext 6 days ago copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts