how.wtf

Access the current index in for loops in Python

· Thomas Taylor

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

1names = ["sally", "mary", "billy"]
2for n in names:
3	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.

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

Output:

10 sally
21 mary
32 billy

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

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

Output:

10 sally
21 mary
32 billy

#python  

Reply to this post by email ↪