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

How to make newlist point to its own memory than that of previous list in python

In python, if we make a list out of an old list, the new list still points to the memory point of old list where the original value is stored. I don’t know what this phenomena is called but can I do what I want to do, if so how come (new to programming).

    z=[[1,2,3],[4,5,6],[7,8,9]]
    y=[]
    for i in range(len(z)):
        y.append(z[i])
    
    y[0][0]='A'
    
    print(y)
    print(z)

#Output:
[['A', 2, 3], [4, 5, 6], [7, 8, 9]]
[['A', 2, 3], [4, 5, 6], [7, 8, 9]]

#The Output I want:
[['A', 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>Solution :

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

As you want to use a new list which point to a new space, you can change your code to this:

    z=[[1,2,3],[4,5,6],[7,8,9]]
    y=[]
    for i in range(len(z)):
        # copy() can return a new list point to a new space, just like the function name.
        y.append(z[i].copy())
    y[0][0]='A'
    
    print(y)
    print(z)

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