Python foreach equivalent [duplicate]
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 Mary1 had2 a3 little4 lamb
Edit#1: Alternate way:
When looping through a sequence, the position index and corresponding value can be retrieved at the sametime using the enumerate()
function.
for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v)
output
0 tic1 tac2 toe