In a ‘for’ loop, the index can be accessed using the built-in enumerate
function. Here’s an example:
scss
list = [1, 2, 3, 4, 5] for index, item in enumerate(list): print(index, item)
This would produce the following output:
0 1
1 2
2 3
3 4
4 5
The enumerate
function takes an iterable as input and returns an iterator that produces pairs (index, element), where index starts from 0 by default, but can be changed by passing the start
parameter to enumerate
.