How to get the index in for loops python with example

This tutorials explains about multiple ways to get an index in for loop iteration in list for loop.

Python for loop index

There are multiple ways we can get index in for loop list.

  • use native for loop with counter

  • Declare counter variable that defaults to zero

  • Iterate each element and print the index and iterated element

  • Increment the counter by 1 inside for loop

Here is an example

counter = 0  
for element in list:  
 print(counter, element)
counter += 1
  • use enumerate function

enumerate function returns iterator with index and element. Index always starts with zero and incremented up to length of an list. It returns tuple of each iteration, first element is an index, second is an element .

Printed the index and element

Here is an example

list = [11, 12, 13,14]
for index, element in enumerate(list):
print(index, element)

Output:

0 11
1 12
2 13
3 14

The above example starts with zero index and print the index with incremented value.

In case, if index want to starts from 1, you can use below

enumerate takes start index defaults to zero. you can pass start=1

list = [11, 12, 13,14]
index = 0
for index, value in enumerate(list, start=1):
print(index, value)

Output:

1 11
2 12
3 13
3 14
  • use range function in for loop

range iterates the elements with count=0 to up to length of the list.

for index in range(len(list)):
print(index, list[index])