Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python replacing all list elements instead of the indexed list element in for loop

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading