Access the current index in for loops in Python

In Python, an iterable may be traversed using a simple for in loop:

1
2
3
names = ["sally", "mary", "billy"]
for n in names:
	print(n)

However, what if the current index is desired?

Access the index in a Python for loop

The recommended pythonic solution is to use the built-in enumerate function.

1
2
3
names = ["sally", "mary", "billy"]
for i, n in enumerate(names):
	print(i, n)

Output:

1
2
3
0 sally
1 mary
2 billy

For contrast, the unidiomatic way to access the current index is by using range:

1
2
3
names = ["sally", "mary", "billy"]
for i in range(len(names)):
	print(i, names[i])

Output:

1
2
3
0 sally
1 mary
2 billy