Home > Back-end >  Why doesn't list change?
Why doesn't list change?

Time:08-18

In Python:

    b = []
    a = np.arange(2)
    b.append(a)
    a = np.arange(4)
    b.append(a)
    print(b) # gives [array([0, 1]), array([0, 1, 2, 3])]

Why doesn't it give [array([0, 1, 2, 3]), array([0, 1, 2, 3])]?

There are a ton of questions going the other way (to make sure the list does not change -- see here or this explanation on referencing and values).

From the links above I would expect b[0] == b[1] because I updated a, but this is not the case. What am I missing?

CodePudding user response:

a = np.arange(4) doesn't update the values inside a, it reassigns the reference to a new array. This is reflected in b, as it has two different arrays as elements.

  • Related