1

Newby question: I'm having trouble figuring out why the code below doesn't work. I'm trying to make a nested list wherein each of the 10 nested lists is in a different order. What I get instead is the same list repeated 10 times in the same order.

So I want: [[1, 2, 4, 3], [4, 2, 3, 1], [2, 4, 3, 1]]

but I get: [[2, 3, 1, 4], [2, 3, 1, 4], [2, 3, 1, 4]]

<pre>from random import shuffle

myList = ["file1", "file2", "file3", "file4"]
longList = []

for x in range(0,10):
    shuffle(myList)
    longList.append(myList)

print(longList)<code>

Thanks in advance!

D

2 Answers2

5

This is because the object references inside the longList are all to the object myList.

As explained here, random.shuffle changes myList in place, so each time you call random.shuffle on it, it overwrites its content.

A solution can be to clone the list each time you shuffle it and several ways are available for this (How to clone a list in Python).

In the following code I choose to slice it :

from random import shuffle

myList = ["file1", "file2", "file3", "file4"]
longList = []

for x in range(0,10):
    shuffle(myList)
    longList.append(myList[:])
Community
  • 1
  • 1
Pierre Cordier
  • 494
  • 3
  • 17
1

Shuffle works inplace, its returning None. It's weird that it's returning same list in a 10 times try. It's possible that you are not doing that enough times, so shuffle returns same results few times in a raw. try to test that for a large number of times. Maybe do:

random.seed(x)

inside the loop.

sramij
  • 4,775
  • 5
  • 33
  • 55
  • This was `random.shuffle`?? OH man I totally did not realize it was *that* shuffle...ugh... OK. I'm deleting mine. +1. Thanks for bringing that up, btw. – idjaw Mar 09 '16 at 23:01
  • Thanks! I have a workaround which is to write each line to a file by putting the shuffle line in side a "with open..." line and then writing to the file on each iteration. But why the above works and my original code doesn't is a mystery to me! (http://pastebin.com/A2p1gXSQ) – user2011285 Mar 09 '16 at 23:04
  • @user2011285 Putting code in the comments like that is really not easy to look at. You can make a pastebin of your code. http://pastebin.com/ – idjaw Mar 09 '16 at 23:06