7.12 Deep Copies

  • When sharing mutable values, sometimes it’s necessary to create a deep copy of the original data
  • Especially important in multi-core programming, where separate parts of your program could attempt to modify your data at the same time, possibly corrupting it
  • array method copy returns a new array object with an independent copy of the original array'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.copy()
In [5]:
numbers2
Out[5]:
array([1, 2, 3, 4, 5])
In [6]:
numbers[1] *= 10
In [7]:
numbers
Out[7]:
array([ 1, 20,  3,  4,  5])
In [8]:
numbers2
Out[8]:
array([1, 2, 3, 4, 5])

Module copy—Shallow vs. Deep Copies for Other Types of Python Objects


©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.