Python overwrites list while changing a copy. How can I keep the original list stored

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dominik

    Python overwrites list while changing a copy. How can I keep the original list stored

    Hey guys,

    hope somebody can help me out of my predicament.

    Basically I have a list whose objects are lists of numbers and I need to use some numerical mathematics on it while keeping the old list to define the break criteria. This is my code so far:
    Code:
    def Numerik(n,m,Field):
        epsilon=1
        Field_new=Field
        while epsilon>0.001:
    #inner nodes (explicit)
            for j in range(1,m):
                Horizontal_North=Field[j-1]
                Horizontal_West_East=Field[j]
                Horizontal_South=Field[j+1]
                Horizontal=Field_new[j]
                for i in range(1,n):
                    North=Horizontal_Nord[i]
                    West=Horizontal_West_East[i-1]
                    East=Horizontal_West_East[i+1]
                    South=Horizontal_South[i]
                    Point=(North+West+East+South)/4
                    Horizontal[i]=Point
                Field_new[j]=Horizontal
                print (Horizontal)
                print (Field[j])
    So basically I used copies to work on. Python still overwrites the original and I get the same output for Horizontal and Field[j] even though it is only supposed to change the Field_new. Can anyone tell me how to keep the old list stored while changing the new one?
    Last edited by bvdet; Nov 10 '10, 02:18 AM. Reason: Add code tags [code]....code goes here....[/code]
  • Mariostg
    Contributor
    • Sep 2010
    • 332

    #2
    I am not sure I quite understand, but consider this.
    When you say y=x[] you create a reference, not a copy. So if you alter y, you alter x.
    To make a copy of x, use y=x[:]

    Comment

    Working...