7.11 Views: Shallow Copies

  • Views “see” the data in other objects, rather than having their own copies of the data
  • Views are shallow copies *array method view returns a new array object with a view of the original array object’s data
In [1]:
import numpy as np
In [2]:
numbers = np.arange(1, 6)
In [3]:
numbers
Out[3]:
array([1, 2, 3, 4, 5])
In [4]:
numbers2 = numbers.view()
In [5]:
numbers2
Out[5]:
array([1, 2, 3, 4, 5])
  • Use built-in id function to see that numbers and numbers2 are different objects
In [6]:
id(numbers)
Out[6]:
4431803056
In [7]:
id(numbers2)
Out[7]:
4430398928
  • Modifying an element in the original array, also modifies the view and vice versa
In [8]:
numbers[1] *= 10
In [9]:
numbers2
Out[9]:
array([ 1, 20,  3,  4,  5])
In [10]:
numbers
Out[10]:
array([ 1, 20,  3,  4,  5])
In [11]:
numbers2[1] /= 10
In [12]:
numbers
Out[12]:
array([1, 2, 3, 4, 5])
In [13]:
numbers2
Out[13]:
array([1, 2, 3, 4, 5])

Slice Views

  • Slices also create views
In [14]:
numbers2 = numbers[0:3]
In [15]:
numbers2
Out[15]:
array([1, 2, 3])
In [16]:
id(numbers)
Out[16]:
4431803056
In [17]:
id(numbers2)
Out[17]:
4451350368
  • Confirm that numbers2 is a view of only first three numbers elements
In [18]:
numbers2[3]
------------------------------------------------------------------------
IndexError                             Traceback (most recent call last)
<ipython-input-18-83bd44fddddf> in <module>
----> 1 numbers2[3]

IndexError: index 3 is out of bounds for axis 0 with size 3
  • Modify an element both arrays share to show both are updated
In [19]:
numbers[1] *= 20
In [20]:
numbers
Out[20]:
array([ 1, 40,  3,  4,  5])
In [21]:
numbers2
Out[21]:
array([ 1, 40,  3])

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.