0

When initializing multiple variables in Python is seems that every variable is different (i.e. not a reference) :

>>>x = y = z = 6
>>>x=5
>>>y=0
>>>print(x,y,z)
>>>5 0 6

but when I am using a numpy array every variable is actually a reference:

import numpy as np
x = y = z = 6*np.ones(1)
x[0] = 5
y[0] = 0
print(x,y,z)
[0.] [0.] [0.]

Why am I seeing this difference?

Benny K
  • 1,957
  • 18
  • 33
  • 1
    It's not only with numpy array but with any mutable object. For eg: you can try with list object – Abdul Niyas P M Oct 19 '22 at 11:45
  • https://stackoverflow.com/questions/16348815/python-assigning-multiple-variables-to-same-value-list-behavior – FlyingTeller Oct 19 '22 at 11:47
  • `x=5` assigns a new value to variable `x`. `x[0]=5` attempts to change an element of the object referenced by `x`. Details of what happens depends the object's class. – hpaulj Oct 19 '22 at 15:09

2 Answers2

1

This is down to a difference in types. Integers are not passed by reference, so each variable gets its own copy of the number. If you look at a different object like a list though:

x = y = z = [0,1,2]
x[0] = 2
print(x, y, x)
[2, 1, 2], [2, 1, 2], [2, 1, 2]

this is also passed by reference, so they all change together.

Strings and integers are the main examples I can think of that you the value, while everything else (I think) is a reference.

Interesting aside related to this: in place operations behave differently for strings and integers vs other objects. For example:

x = 1
print(id(x))
x += 1
print(id(x))

behaves differently to

y = []
print(id(y))
y += [1]
print(id(y))

You can see in the first instance a new object is now assigned to the x variable, while in the second the y variable is the same object.

PirateNinjas
  • 1,908
  • 1
  • 16
  • 21
1

You need to make copies:

a = 6*np.ones(1)

x, y, z = (a.copy() for _ in range(3))
# or directly
# x, y, z = (6*np.ones(1) for _ in range(3))

x[0] = 1
(x, y, z)

output:

(array([1.]), array([6.]), array([6.]))
mozway
  • 194,879
  • 13
  • 39
  • 75