0

I can t understand why 'matriz' is being modified, how am i supposed to modify 'matriznew' without affecting the original one?

matriz = [[1.0, 7.0, 0, 5.0],
        [1.125, 1.0, 0.25, 0.875],
        [0, 0.6, 1.0, 0.2]]

matriznew = matriz
for line in range(len(matriznew)):
        matriznew[line].pop(-1)


print(matriznew)
print(matriz)

OUTPUT:

[[1.0, 7.0, 0], [1.125, 1.0, 0.25], [0, 0.6, 1.0]]

[[1.0, 7.0, 0], [1.125, 1.0, 0.25], [0, 0.6, 1.0]]

2 Answers2

2

You should create a copy of the list, instead of use a normal assignment:

matriz = [[1.0, 7.0, 0, 5.0],
        [1.125, 1.0, 0.25, 0.875],
        [0, 0.6, 1.0, 0.2]]

matriznew = matriz.copy()
for line in range(len(matriznew)):
        matriznew[line].pop(-1)


print(matriznew)
print(matriz)

EDIT: As @SpearAndShield points out, unfortunately this doesn't work for nested lists. In this case you can use a recursive copy function like this

def copy_recursive(parent, l):
    new_l=[]
    for el in l:
        if type(el) != list:
            new_l.append(el)
        else:
            new_l.append(copy_recursive(l, el))
    
    return new_l

...

matriznew = copy_recursive([], matriz)
...
Marco Balo
  • 336
  • 2
  • 9
1

matriznew and matrix point to the same location in memory, that's why when you change one, you change both.

try this:

matriznew = matriz.copy()
dsghrg
  • 98
  • 2
  • 8