Home > front end >  How to make newlist point to its own memory than that of previous list in python
How to make newlist point to its own memory than that of previous list in python

Time:12-26

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]]

CodePudding user response:

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)

  • Related