5

I'm using python and want to shuffle a copied list that I write after that into a txt file (see my code below).

Why does the shuffle function randomize the original list, too? I only use the copy for the function call.

Any ideas? Thank you !

from random import shuffle

def shuffleList2txt(myList):
    shuffle(myList)

    f = open('randList.txt','w')
    f.write(str(liste))
    f.close()

    return(myList)


liste = [1,2,3,4,5,6,7,8,9,10]
copy = liste
shuffledList = shuffleList2txt(copy)

liste and shuffledList are the same ! Why? liste should be the original one and shuffledList should be the shuffled list.... :)

Chanda Korat
  • 2,263
  • 2
  • 18
  • 22
HKC72
  • 434
  • 1
  • 8
  • 18
  • not sure if you read [this](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) before, but I think it's good thing to know in your case. – stucash Dec 11 '17 at 10:33
  • 1
    You and your partner have a dog. You call her "Jo" and your partner calls her "Krok", Now your partner calls a grooming service to trim the hair of Krok, do you expect that when you'll get home Jo has still long hair? the list object, though named in two different manners, is still the same old dog! please refer to [this question](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list?s=1|749.8298) (or any of the tens of answers on this topic) to overcome this issue. – gboffi Dec 11 '17 at 10:37
  • Haha... Thanks gboffi for this beautiful explanation :) – HKC72 Dec 11 '17 at 11:37

1 Answers1

23

random.shuffle works in place. Of course you could make a copy of the list prior to shuffling, but you'd be better off with random.sample, by taking a sample ... of the whole list:

>>> l = [1,2,3,4]
>>> random.sample(l,len(l))
[3, 1, 2, 4]
>>> l
[1, 2, 3, 4]

so assigning the result of random.sample gives you a new, shuffled list without changing the original list.

Jean-François Fabre
  • 131,796
  • 23
  • 122
  • 195
  • 1
    Congratulations for the right answer to the wrong question! – gboffi Dec 11 '17 at 10:48
  • Thank you Jean-Francois ! You showed a nice solution ! I also checked the other topics and understood the Problem with cloning lists. – HKC72 Dec 11 '17 at 11:39