Why doesn't list change?

Question:

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?

Asked By: Physics Enthusiast

||

Answers:

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.

Answered By: Bill the Lizard
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.