Access the Index in Python 'for' Loops

Kontext Kontext event 2022-07-15 visibility 168
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.

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts