#!/usr/bin/env python # coding: utf-8 # # Lesson 4 - Copies and Views # The original tutorial may be found [here](http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-1529ae93dd5d431ffe3a1001a4ab1a394e70a5f2). # When operating and manipulating arrays, their data is sometimes copied into a new array and sometimes not. This is often a source of confusion for beginners. There are three cases: # # - No Copy at All # - View or Shallow Copy # - Deep Copy # In[1]: import numpy as np # ## No Copy at All # Simple assignments make no copy of array objects or of their data. # In[2]: a = np.arange(12) # In[3]: a # In[4]: b = a # no new object is created # In[5]: b is a # a and b are two names for the same ndarray object # In[6]: b.shape = 3, 4 # In[7]: b # In[8]: a # Python passes mutable objects as references, so function calls make no copy. # In[9]: def f(x): print id(x) # In[10]: id(a) # In[11]: f(a) # ## View or Shallow Copy # Different array objects can share the same data. The view method creates a new array object that looks at the same data. # In[12]: c = a.view() # In[15]: c is a # In[16]: c.base is a # c is a view of the data owned by a # In[17]: c.flags.owndata # In[18]: c.shape = 2,6 # a's shape doesn't change # In[19]: a # In[20]: c # In[22]: c[0,4] = 1234 # a's data changes # In[23]: a # In[25]: c # ## Deep Copy # The copy method makes a complete copy of the array and its data. # In[27]: d = a.copy() # a new array object with new data is created # In[28]: d is a # In[29]: d.base is a # d doesn't share anything with a # In[30]: d[0,0] = 9999 # In[31]: a # In[32]: d # # Conclusion # We have now completed the Tutorial [Lesson 4 - Copies and Views](http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-1529ae93dd5d431ffe3a1001a4ab1a394e70a5f2)