'python modifying uncalled lists [duplicate]
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]]
Solution 1:[1]
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)
...
Solution 2:[2]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | dsghrg |
