To access the index value in a Python for
loop, use the enumerate()
function. It adds an index to each item being iterated over. Here’s an example:
python
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
The enumerate()
function starts indexing at 0 by default, but you can specify a custom starting index:
python
for index, fruit in enumerate(fruits, start=1):
print(f"Index: {index}, Fruit: {fruit}")
This approach is concise and improves readability when you need both the index and the item during iteration.