0

Code:

import numpy as np

def f(a):
    return np.array([0, 1])

N_x, N_y = 4, 3

U = V = np.zeros((N_x, N_y))

for n_y in range(N_y):
    for n_x in range(N_x):
        U[n_x, n_y], V[n_x, n_y] = f(0)

print(U, V)

This gives the unexpected output:

[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]] [[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

But if I use

U = np.zeros((N_x, N_y))
V = np.zeros((N_x, N_y))

instead of U = V = np.zeros((N_x, N_y)), I get the following expected result.

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]] [[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

Question: What has gone awry here?

Atom
  • 125
  • 4

1 Answers1

1

With multiple assignment you get only one object assigned to both U and V variables, so effectively you're then doing this:

for n_y in range(N_y):
    for n_x in range(N_x):
        U[n_x, n_y], U[n_x, n_y] = f(0)

print(U, U)
Ilia Novoselov
  • 343
  • 2
  • 4
  • Then why does the following work? `A = B = np.array([1])` `A = np.array([0])` This prints `[0] [1]` as expected. – Atom Nov 22 '20 at 10:16
  • 1
    Because then you assign a new object to the A variable (but B still points to the first object). – Ilia Novoselov Nov 22 '20 at 10:28