Its also interesting to observe this
To iterate over the indices of a sequence, you can combine range()
and len()
as follows:
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print(i, a[i])
output
0 Mary
1 had
2 a
3 little
4 lamb
Edit#1: Alternate way:
When looping through a sequence, the position index and corresponding value can be retrieved at the same
time using the enumerate()
function.
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
output
0 tic
1 tac
2 toe