0

When I shuffle several sublists they come out in the same order. I'm sure I can reseed it with a random number each time, but everything I read implies that I shouldn't have to.
Code:

test=[list(range(10))]*5
import random
for x in test:
    random.shuffle(x)

print(test)

Results:

[[0, 8, 9, 6, 1, 2, 7, 4, 5, 3], [0, 8, 9, 6, 1, 2, 7, 4, 5, 3], [0, 8, 9, 6, 1, 2, 7, 4, 5, 3], [0, 8, 9, 6, 1, 2, 7, 4, 5, 3], [0, 8, 9, 6, 1, 2, 7, 4, 5, 3]]

Why isn't shuffle producing different orders?

Kalev Maricq
  • 617
  • 1
  • 7
  • 24
  • Yep, had just realized this myself. That's definitely it. – Kalev Maricq Jan 23 '20 at 21:54
  • When you do: `test=[list(range(10))]*5` you're creating 5 references to the **same** list - the dupe above linked by @Peter explains this fairly well – Jon Clements Jan 23 '20 at 21:54
  • 1
    I'd probably doing what you're doing go for something like define the candidate space - eg: `r = range(10)` (convenient as it can compute on the fly and doesn't really occupy space and can be re-used), and then build it up something like: `test = [random.sample(r, len(r)) for _ in range(5)]` – Jon Clements Jan 23 '20 at 22:03

1 Answers1

3

It's not about shuffling, it's about the way you define the list.

>>> test=[list(range(3))]*2
>>> test
[[0, 1, 2], [0, 1, 2]]
>>> test[0][0]=111
>>> test
[[111, 1, 2], [111, 1, 2]]

So, in practice you are shuffling the same list at each time since they all reference the same list.

abc
  • 11,579
  • 2
  • 26
  • 51