7.12 Deep Copies

Though views are separate array objects, they save memory by sharing element data from other arrays. However, when sharing mutable values, sometimes it’s necessary to create a deep copy with independent copies of the original data. This is 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.

The array method copy returns a new array object with a deep copy of the original array object’s data. First, let’s create an array and a deep copy of that array:

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])

To prove that numbers2 has a separate copy of the data in numbers, let’s modify an element in numbers, then display both arrays:

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])

As you can see, the change appears only in numbers.

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

In previous chapters, we covered shallow copying. In this chapter, we’ve covered how to deep copy array objects using their copy method. If you need deep copies of other types of Python objects, pass them to the copy module’s deepcopy function.

tick mark Self Check

  1. (True/False) The array method copy returns a new array that is a view (shallow copy) of the original array.
    Answer: False. The array method copy produces a deep copy of the original array.

  2. (True/False) Module copy provides function deep_copy, which returns a deep copy of its argument.
    Answer: False. The name of the function is deepcopy.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.142.146