Accessing the index while iterating a sequence with a for loop in Python

While programming in Python, there may be situations where you may need to access the index while iterating a sequence with a for loop along with the element of the sequence. For such situations, you can use Python’s built-in function enumerate(). Here is an example:

sample_list = ['A001', 'A002', 'A003', 'A005']

for i, val in enumerate(sample_list):
    print(f"Index: {i}, Value: {val}")
Accessing the index while iterating a sequence with a for loop in Python

This technique will be useful when you need to access both the elements and its indexes while iterating a sequence in Python.

Reference

  • More about enumerate built-in function at Python Docs.


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.