Python Forum

Full Version: Variable assignment wierdness with Memory
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I am having an issue with variable assignment or maybe memory with my computer. I am assigning V_new the value of V, then I change V_new without changing V, but when I print V before and after this, I get changes. I am using Sublime as my editor and am simply running my file through the terminal on my computer. I don't understand why this is happening. Please see my code and output here:
LENGTH = 10
WIDTH = 10

a = np.linspace(0, 5, LENGTH)

V = np.empty((LENGTH, WIDTH))
for i in range(WIDTH):
	V[i] = a

# Boundary Conditions
V[:, LENGTH - 1] = 5
V[:, 0] = 0
V[0, :] = 0
V[WIDTH - 1, :] = 0

V_new = V

print(pd.DataFrame(V))

for i in range(1, LENGTH - 1):
	for j in range(1, WIDTH - 1):
		V_new[i, j] = 0.25*(V_new[i + 1, j] + V_new[i - 1, j] + V_new[i, j + 1] + V_new[i, j - 1])

print(pd.DataFrame(V))
The output is the following:

0 1 2 3 4 5 6 7 8 9
0 0.0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.0
1 0.0 0.555556 1.111111 1.666667 2.222222 2.777778 3.333333 3.888889 4.444444 5.0
2 0.0 0.555556 1.111111 1.666667 2.222222 2.777778 3.333333 3.888889 4.444444 5.0
3 0.0 0.555556 1.111111 1.666667 2.222222 2.777778 3.333333 3.888889 4.444444 5.0
4 0.0 0.555556 1.111111 1.666667 2.222222 2.777778 3.333333 3.888889 4.444444 5.0
5 0.0 0.555556 1.111111 1.666667 2.222222 2.777778 3.333333 3.888889 4.444444 5.0
6 0.0 0.555556 1.111111 1.666667 2.222222 2.777778 3.333333 3.888889 4.444444 5.0
7 0.0 0.555556 1.111111 1.666667 2.222222 2.777778 3.333333 3.888889 4.444444 5.0
8 0.0 0.555556 1.111111 1.666667 2.222222 2.777778 3.333333 3.888889 4.444444 5.0
9 0.0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.0
0 1 2 3 4 5 6 7 8 9
0 0.0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.0
1 0.0 0.416667 0.798611 1.171875 1.542969 1.913520 2.283936 2.654317 3.024690 5.0
2 0.0 0.520833 1.024306 1.521267 2.016059 2.510173 3.004083 3.497933 3.991767 5.0
3 0.0 0.546875 1.087240 1.624349 2.160102 2.695346 3.230413 3.765420 4.300408 5.0
4 0.0 0.553385 1.104601 1.654460 2.203640 2.752524 3.301290 3.850011 4.398716 5.0
5 0.0 0.555013 1.109348 1.663174 2.216704 2.770085 3.323399 3.876686 4.429962 5.0
6 0.0 0.555420 1.110636 1.665675 2.220595 2.775448 3.330267 3.885072 4.439869 5.0
7 0.0 0.555522 1.110984 1.666387 2.221745 2.777076 3.332391 3.887699 4.443003 5.0
8 0.0 0.416658 0.798577 1.171797 1.542830 1.913310 2.283648 2.653948 3.024238 5.0
9 0.0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.0
This is expected behavior, because numpy arrays are mutable.
The same is true for lists. If you create a list, e.g. x = [1, 2, 3], assign it to another variable y=x (create a new reference, exactly), and change y, e.g. y[0]=10, x will change too (x[0] will be 10).