I'm trying to create an randomized list of keys by iterating:
import randomkeys = ['1', '2', '3', '4', '5']
random.shuffle(keys)
print keys
This works perfect. 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 am getting 10 times of the same shuffle?! Obviously something is fundamentally wrong here... Thanks in advance.
The problem is that you are shuffling the list in place and then adding the reference of the list to the combined list. Thus you end up with same list structure 10 times.
"Fundamental change" is that the list has to be copied before appending it.
Here is a bit more "pythonic" way of achieving the same result with list comprehension.
import randomdef shuffleACopy(x):b = x[:] # make a copy of the keysrandom.shuffle(b) # shuffle the copyreturn b # return the copykeys = [1,2,3,4,5,6,7,8]
a = [shuffleACopy(keys) for x in range(10)]
print(a)