-3

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?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • Thanks! Is this related to immutable vs mutable values? – Physics Enthusiast Aug 17 '22 at 17:01
  • 1
    Kinda, yeah. Like you noted below, it has more to do with if you changed the value that is referenced by a variable vs. changing the actual "pointer". Immutable values _can't_ be changed, so any time you do this it does the latter. – Pranav Hosangadi Aug 17 '22 at 17:14

1 Answers1

2

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880