Python array element assignment
I am confused with a simple case about array variable assignment in Python, and hope some one could help me check it.
In my understanding, if a is a list, b just copied the reference of a, and when you edit b, a would be modified as well. Meanwhile, you could use the
is operator to check their ids. For example:
a = ["a", ["a", "b"]] b = a b.append("c")
Then, it would return
True, when I use
In : b is a Out: True
However, if a and b are an arrays,
import numpy as np a = np.identity(3) b = a[0, :]
Afterwards, when I use
is to check, it returns
False, but when I edited b, a would be modified as well:
In : b is a Out: False In : a Out: array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) In : b Out: array([0., 1., 0.]) In : b *= 2 In : b Out: array([0., 2., 0.]) In : a Out: array([[1., 0., 0.], [0., 2., 0.], [0., 0., 1.]])
Basically, I think if
False, variables would have different ids and references, which means that they are independent, but it seems wrong right now, could anyone help me to check it?
Numpy arrays work differently than Python lists. In your example, b is a numpy view of the first row of a, which is not the same as a pointer to the first element a.
By the way, you can check the id of each of your variables by doing
Accessing a slice of the array creates a view.
a[0,:]are distinct views, even though they view the same part of the array
a, so their id values are different even though their underlying references are the same.
The id of an object is technically distinct from what it's referencing, so objects with the same id will reference the same data but objects with the same reference don't necessarily have the same id