I want to replace the kth element of the kth element of the list.
E.g.,
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
to
[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
BUT python does not seem to want to do that and instead is replacing each value for each element.
I run this:
# Triangle Vertices
V = [[0, 1], [-1, 0], [1, 0]]
# Triangles (indices of V in clockwise direction)
T = [[1, 0, 2]]
# Creating sub-triangles
bary_point = [0, 0.5]
v_list = []
for t in T:
print(t)
for k in range(3):
v_list.append(V)
v_list[k][k] = bary_point # <-- This line
print('v_list: ')
print(v_list)
and it produces this:
v_list:
[[[0, 0.5], [0, 0.5], [0, 0.5]],
[[0, 0.5], [0, 0.5], [0, 0.5]],
[[0, 0.5], [0, 0.5], [0, 0.5]]]
but I want this:
v_list:
[[[0, 0.5], [-1, 0], [1, 0]],
[[0, 1], [0, 0.5], [1, 0]],
[[0, 1], [-1, 0], [0, 0.5]]]
Am I doing something wrong? I am on Python 3.10.0
Thank you.
EDIT Solution: Change
v_list.append(V)
to
v_list.append(V.copy())
Thank you!
CodePudding user response:
You are appending the same reference to the list V
, and when you change v_list[k][k]
you are changing V
, one solution would be to append a copy of the list, by using V.copy()
as argument to append
.