Python - Getting the index with a for loop

By using the built-in function enumerate, you can get both the index and the value of a list at the same time. enumerate is a built-in function that takes an iterable object (such as a list, tuple, or string) as input, assigns an index to each element, and returns a pair of the index and element.

Getting a sequence number with enumerate

sampleList = ['data1', 'data2', 'data3']

for index, value in enumerate(sampleList):
    print(f'index = {index}  value = {value}')
Sample code execution result
index = 0  value = data1
index = 1  value = data2
index = 2  value = data3
Execution result
Execution result

Specifying the initial value of the sequence number

sampleList = ['data1', 'data2', 'data3']

# Start the sequence number from 1
for index, value in enumerate(sampleList, 1):
    print(f'index = {index}  value = {value}')
Sample code execution result
index = 1  value = data1
index = 2  value = data2
index = 3  value = data3
Execution result
Execution result

Reference

Test Environment