0

I want to copy list values to another list because I modify the original one and use the new one. Bu t whatever I try it will alwasy assign reference not value.

class Chromosome:

    def __init__(self):
        self.matrix = [[0 for x in range(LENGTH)] for y in range(LENGTH)]

class Population:

    def __init__(self, start):
        self.start = start
        self.chromosomes = []

    def crossover(self):
        for index in range(0, POPULATION_SIZE - 1, 2):
           swap_point = random.randint(7, 10)
           matrix1 = self.chromosomes[index].matrix
           matrix2 = self.chromosomes[index + 1].matrix
           self.chromosomes[index].crossover(matrix2, swap_point)
           self.chromosomes[index + 1].crossover(matrix1, swap_point)

The following lines is that ı wan to assign values not reference

matrix1 = self.chromosomes[index].matrix[:] and matrix2 = self.chromosomes[index + 1].matrix[:]

I tried followings

list(self.chromosomes[index + 1].matrix)

self.chromosomes[index + 1].matrix[:]

self.chromosomes[index + 1].matrix.copy()

How can I get values of the chromosome to matrix1 and matrix2?

Hakan SONMEZ
  • 2,176
  • 2
  • 21
  • 32

1 Answers1

1

You can use deepcopy() from copy library:

from copy import deepcopy

A = [[1,2], [3,4]]
B = deepcopy(A)
A[0][0] = 5

print(B)

# output: [[1, 2], [3, 4]]
bn_ln
  • 1,648
  • 1
  • 6
  • 13