3

I would like to create a random double loop in Python.

For example, for (N,N)=(2,2) the program should give:

0 1
0 0
1 1
1 0

Or another example

0 0
1 1
1 0
0 1

So far, I have done this:

r1 = list(range(2))
r2 = list(range(2))
random.shuffle(r1)
random.shuffle(r2)
for i in r1:
    for j in r2:
        # Do something with i

This, however, does not give the desired result, because I want i's to be shuffled too and not give for example all (1,x) sequentially. Any ideas?

1
  • Create all the outputs first and then shuffle Commented Nov 22, 2019 at 18:38

1 Answer 1

5

Shuffle the product of the ranges, not each individual range.

import itertools


pairs = list(itertools.product(r1, r2))  # [(i,j) for i in r1 for j in r2]
random.shuffle(pairs)

for i, j in pairs:
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.