user3741713 user3741713 - 3 months ago 29
Python Question

python random shuffle while loop

I'm trying to fill lists with permutations of the same initial list. I don't understand why the following is not working.

parts = [[],[]]
while len(parts[-1]) < 2:
newval = random.choice([[1,2,3,4],[5,6,7,8]])
for part in parts:
random.shuffle(newval)
part.append(newval)


Expected result would be something like:
[[[6,7,8,5],[1,3,4,2]],[[5,8,6,7],[4,2,3,1]]]

Answer

random.shuffle works in-place and consequently modifies newval. You have to make a copy when appending to part otherwise the same list (or list reference) is shuffled and stored in part.

import random

parts = [[],[]]
while len(parts[-1]) < 2:
  newval = random.choice([[1,2,3,4],[5,6,7,8]])
  for part in parts:
    random.shuffle(newval)
    part.append(newval[:])

print(parts)

possible outputs:

[[[3, 1, 2, 4], [5, 7, 6, 8]], [[1, 2, 4, 3], [6, 7, 5, 8]]]
[[[1, 3, 2, 4], [4, 2, 1, 3]], [[2, 4, 3, 1], [4, 3, 2, 1]]]
[[[7, 5, 6, 8], [3, 2, 4, 1]], [[8, 5, 6, 7], [1, 4, 3, 2]]]
Comments