In Python, you can access the index of elements in a list or other iterable using a for
loop in combination with the enumerate()
function. enumerate()
returns both the index and the value of each element, which allows you to access both within the loop.
Here’s an example:
my_list = ['a', 'b', 'c', 'd']
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
Output:
Index: 0, Value: a
Index: 1, Value: b
Index: 2, Value: c
Index: 3, Value: d
In this example:
enumerate(my_list)
gives a sequence of tuples(index, value)
.index
is the current index, andvalue
is the corresponding value at that index.