Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

How to access the index value in a 'for' loop?

Solution:

In Python, you can use the enumerate function to access the index and the value of items in a for loop.

Here's an example:


my_list = ["apple", "banana", "cherry"]

for index, value in enumerate(my_list):
    print(f"Index: {index}, Value: {value}")

First, enumerate(my_list) returns pairs of index and value.

Then, the for loop iterates over these pairs, and in each iteration, the index gets the index of the current item, and the value gets the actual value.

Do you want to know more about Python programming? Check out our blogs!