Accessing the index in 'for' loops

When iterating over a sequence with a for loop in Python, it is often useful to access the index of each item in addition to the item itself. This can be achieved by using the built-in enumerate() function or by manually keeping track of the index using a separate counter variable. In this article, we will explore both approaches and provide examples to illustrate how to access the index in for loops.

Using the enumerate() function

The enumerate() function in Python allows you to iterate over a sequence while simultaneously accessing both the index and the value of each item. It returns an iterator object that produces tuples containing the index and the value for each iteration. Here's how you can use it:

xs = [8, 23, 45]

for index, value in enumerate(xs):
    print("item #{} = {}".format(index + 1, value))

The enumerate() function takes an optional start parameter that specifies the starting value for the index. By default, it starts from 0. In the example above, we added 1 to the index when printing it to display the output as item #1, item #2, item #3 instead of item #0, item #1, item #2.

Here's the output of the above code:

item #1 = 8
item #2 = 23
item #3 = 45

Manually keeping track of the index

If you don't want to use the enumerate() function, you can manually keep track of the index by using a separate counter variable. Here's an example:

xs = [8, 23, 45]
index = 1

for x in xs:
    print("item #{} = {}".format(index, x))
    index += 1

In this example, we initialize the index variable to 1 before the loop starts and increment it by 1 after each iteration. This allows us to display the desired output as item #1, item #2, item #3.

Here's the output of the above code:

item #1 = 8
item #2 = 23
item #3 = 45

Conclusion

Accessing the index in for loops can be achieved using the enumerate() function or by manually keeping track of the index using a separate counter variable. Both approaches allow you to iterate over a sequence and access both the index and the value of each item. The enumerate() function is a more concise and Pythonic way to accomplish this task, while manually keeping track of the index gives you more control over the indexing process.