How to Access the Index in a Python for Loop?

python

In Python, you can access the index of a loop using the built-in function enumerate(). Here's an example:

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

for index, fruit in enumerate(my_list):
    print(index, fruit)

# Output:
# 0 apple
# 1 banana
# 2 cherry

In the example above, enumerate() returns a tuple with two values for each iteration of the loop: the index of the current item (index) and the value of the current item (fruit). The loop then assigns these values to separate variables (index and fruit) for each iteration.

You can then use the index variable to access elements of other lists or do any other operations involving the index.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?