loop and print index of a list in python

To loop through a list and print the index of each item in the list, you can use the enumerate() function in Python. Here's an example:

main.py
my_list = ['apple', 'banana', 'cherry', 'date']

for index, item in enumerate(my_list):
    print(f'The item at index {index} is {item}')
138 chars
5 lines

This will output:

main.py
The item at index 0 is apple
The item at index 1 is banana
The item at index 2 is cherry
The item at index 3 is date
117 chars
5 lines

In the loop, enumerate(my_list) returns a sequence of tuples, where each tuple contains an index and a corresponding item from the list. The for loop unpacks each tuple into the index and item variables, which you can then use to print the desired output.

related categories

gistlibby LogSnag