0

I'm trying to copy a matrix and modify it without modifying the original one

I know that I can't just make

new = old

otherwise, python will not copy the list referenced by new. We just created a new tag old and attached it to the list pointed by new. I've tried methods such as

new = list(old)
new = old[:]
new = old.copy()

and even so, it doesn't work.

the piece of my code where it happens is this:

mat = []
my_inputs()
for a in range(n):
    gen = mat[:]
    for l in range(len(gen)):
        for c in range(len(gen[0])):
            if mat[l][c] == " " and cna([l, c], mat) == 3:
                gen[l][c] = "@"
            elif mat[l][c] == "@" and cna([l, c], mat) >= 4:
                gen[l][c] = " "

By the way those lists are actually vectors.

nyi
  • 3,123
  • 4
  • 22
  • 45

2 Answers2

0

Have you tried using deepcopy? https://docs.python.org/3.6/library/copy.html#copy.deepcopy

from copy import deepcopy

test = [list(range(3))]

test_copy = test.copy()
test_deepcopy = deepcopy(test)

test_copy[0][0] = 21
test_deepcopy[-1][-1] = 42

print(f'Original: {test}')
print(f'With copy: {test_copy}')
print(f'With deepcopy: {test_deepcopy}')

>>>

Original: [[21, 1, 2]]
With copy: [[21, 1, 2]]
With deepcopy: [[0, 1, 42]]
Sebastian Loehner
  • 1,302
  • 7
  • 5
-2

Try this snippet

newList.clear(); //clear the list

newList.addAll(OldList); // Add the all data of the old List to the new List

Dinjit
  • 101
  • 1
  • 11