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[1]

Then, it would return True, when I use

In [7]: b is a[1]
Out[7]: 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 [14]: b is a[1]
Out[14]: False
In [15]: a
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
In [16]: b
Out[16]: array([0., 1., 0.])
In [17]: b *= 2
In [18]: b
Out[18]: array([0., 2., 0.])
In [19]: a
array([[1., 0., 0.],
       [0., 2., 0.],
       [0., 0., 1.]])

Basically, I think if is returns 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?

Many thanks!

2 answers

  • answered 2018-10-23 01:15 Brian Amadio

    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 id(b) or id(a[0]) for example.

  • answered 2018-10-23 01:28 Michael

    Accessing a slice of the array creates a view. b and 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