Reputation: 71
My task is to shuffle numbers and that append to array. My program is shuffling it but only once.
order = []
population = []
i = 0
for i in range(i,M):
order.append(i)
i = 0
for i in range(i,10):
random.shuffle(order)
population.append(order)
my input = [[1, 0, 2], [1, 0, 2], [1, 0, 2], [1, 0, 2], [1, 0, 2]]
expected input = [[0, 2, 1], [1, 0, 2], [0, 2, 1], [2, 0, 1], [2, 1, 0]]
Upvotes: 1
Views: 234
Reputation: 1598
You have to use copy because you are appending the same reference over and over again, so you are actually shuffling order
but it is affecting to every instance in population
import random
import copy
order = []
population = []
i = 0
for i in range(i,M):
order.append(i)
i = 0
for i in range(i,10):
random.shuffle(order)
population.append(copy.deepcopy(order))
print(population)
Upvotes: 0
Reputation: 17322
you are appending references to the same list order
so you have one list in the final result, you could use:
for i in range(i,10):
new_o = order.copy()
random.shuffle(new_o)
population.append(new_o)
Upvotes: 1