The mysterious formula is quite simple:
{count} = {index of current loop} + {size of current loop}*{count of parent loop}
As an example, consider a single loop:
x = 5
for i in range(x):
count = i
To be explicit, count = i + x*0
but the second term is irrelevant because there is no parent loop. An example of two loops might be more illuminating:
x = 5
y = 6
for i in range(x):
for j in range(y):
count = j + y*(i)
Notice that I put i
in parentheses to emphasize that it is the {count of parent loop}
. This formula can be easily expanded to a third loop:
x = 5
y = 6
z = 7
for i in range(x):
for j in range(y):
for k in range(z):
count = k + z*(j + y*(i))
and so on...