By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,035 Members | 1,388 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,035 IT Pros & Developers. It's quick & easy.

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

P: n/a
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:
Expand|Select|Wrap|Line Numbers
  1. def Numerik(n,m,Field):
  2.     epsilon=1
  3.     Field_new=Field
  4.     while epsilon>0.001:
  5. #inner nodes (explicit)
  6.         for j in range(1,m):
  7.             Horizontal_North=Field[j-1]
  8.             Horizontal_West_East=Field[j]
  9.             Horizontal_South=Field[j+1]
  10.             Horizontal=Field_new[j]
  11.             for i in range(1,n):
  12.                 North=Horizontal_Nord[i]
  13.                 West=Horizontal_West_East[i-1]
  14.                 East=Horizontal_West_East[i+1]
  15.                 South=Horizontal_South[i]
  16.                 Point=(North+West+East+South)/4
  17.                 Horizontal[i]=Point
  18.             Field_new[j]=Horizontal
  19.             print (Horizontal)
  20.             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?
Nov 10 '10 #1
Share this Question
Share on Google+
1 Reply


100+
P: 332
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[:]
Nov 10 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.