colors = ['red', 'green', 'blue'] # Loop over the elements in the list and print their index and value for i, color in enumerate(colors): print(f'{i}: {color}')
0: red 1: green 2: blue
To access the index of an element in a list or other iterable object in a for loop in Python, you can use the enumerate() function. This function takes an iterable object as an argument and returns an iterator that yields pairs of values, consisting of the index and the element at that index.
In the example above, the enumerate() function is used to loop over the elements in the colors list. For each element, the enumerate() function returns a pair of values consisting of the element's index (i) and the element itself (color). These values are then printed to the screen.
The enumerate() function is a convenient and efficient way to access the index of an element in a for loop. It is especially useful when you need to loop over a list and use the index of each element to access other data or perform other operations.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.