0

I am trying to create a lists with three other lists in it, but the lists are linked so when i change one of the sublists in the list, it changes all of them.

I tried using [:] which i have heard unlinks lists when creating them, but that does not seem to work in my case, any suggestions?

matrix = [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]

list_of_matrixes = []

for _ in range(3):
    list_of_matrixes.append(matrix[:])

list_of_matrixes[0][0][0][0] = 1

for i in list_of_matrixes:
    print(i)

1 Answers1

2

The slice [:] only copies one level, you need a deepcopy

import copy
for _ in range(3):
    list_of_matrixes.append(copy.deepcopy(matrix))
azro
  • 53,056
  • 7
  • 34
  • 70