For loop with multiple increment statements in Python

Viewed 344

In C, for loops can have multiple 'increment' statements. For example:

int j;
unsigned int r;

r  = 4;  // in reality, a non-trivial initialization

for (j = 0; j < 1000; j++, r++)  {
    if (r == 8)
        r = 0;

    printf("j = %d, r = %u\n", j, r);

    // ... do some work, including continue statements

}

In the above loop j and r are increased simultaneously in every iteration of the loop.

Now I wonder how I can replicate the same in Python. So far I've found the following solution, which is not as elegant.

r = 4 # actually a complicated initialization

r = r - 1

for j in range(1000):
    r = r + 1
    if r == 8:
        r = 0
     # the rest of the loop

The Python version is clearly uglier (particularly because of decrementing r by 1 before the start of the loop).

Is there a nicer way to do so?

1 Answers

There is some way to iterate in parallel :

from itertools import product
min_i, min_j = 1, 2
max_i, max_j = 3, 4
for i, j in product(iter(range(min_i, max_i + 1)),iter(range(min_j, max_j + 1))):
    print(i,j)

The result :

1 2
1 3
1 4
2 2
2 3
2 4
3 2
3 3
3 4

If you mean something else, let me know that. I will correct my answer then.

Related