Python list not moving in loop

I am trying to create a randomized list of keys by iterating:

import random keys = ['1', '2', '3', '4', '5'] random.shuffle(keys) print keys 

This works great. However, if I put it in a loop and capture the output:

 a = [] for x in range(10): random.shuffle(keys) a.append(keys) 

I get 10 times the same shuffle ?! Obviously, something here is fundamentally wrong ... Thanks in advance.

+7
source share
2 answers

The problem is that you are shuffling the list into place, and then adding the list reference to the combined list. This way you get the same list structure 10 times. A “fundamental change” is that the list must be copied before adding it.

Here is a slightly more “pythonic” way to achieve the same result with list comprehension.

  import random

 def shuffleACopy (x):
         b = x [:] # make a copy of the keys
         random.shuffle (b) # shuffle the copy
         return b # return the copy

 keys = [1,2,3,4,5,6,7,8]
 a = [shuffleACopy (keys) for x in range (10)]
 print (a)
+16
source

Hypnos has already answered a very correct solution, so I’m just giving you a better way to understand what happened and how to identify such things in the future:

 import random keys = ['1', '2', '3', '4', '5'] a = [] for x in range(10): random.shuffle(keys) a.append(keys) print a 

gives:

 [['4', '5', '3', '2', '1']] [['2', '5', '1', '4', '3'], ['2', '5', '1', '4', '3']] [['2', '5', '4', '1', '3'], ['2', '5', '4', '1', '3'], ['2', '5', '4', '1', '3']] [['5', '4', '3', '1', '2'], ['5', '4', '3', '1', '2'], ['5', '4', '3', '1', '2'], ['5', '4', '3', '1', '2']] [['1', '4', '3', '2', '5'], ['1', '4', '3', '2', '5'], ['1', '4', '3', '2', '5'], ['1', '4', '3', '2', '5'], ['1', '4', '3', '2', '5']] [['2', '3', '4', '1', '5'], ['2', '3', '4', '1', '5'], ['2', '3', '4', '1', '5'], ['2', '3', '4', '1', '5'], ['2', '3', '4', '1', '5'], ['2', '3', '4', '1', '5']] [['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3']] [['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1']] [['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1']] [['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1']] 

Also, by noting that random.shuffle nothing, you may start to suspect that the conversion was done in place.

+3
source

All Articles