-1

I'm having an issue with IPython. I can't seem to find any related issues online (perhaps due to inadequate description).

Here's an example from an IPython session using Numpy as np:

x1 = np.array([1.0, 1.0, 1.0, 1.0])
x2 = x1
x2[2] = x2[2] + 0.01

Now, if I look within the session at what's stored in x1 and x2, I see the same thing for both:

array([1. , 1. , 1.01, 1. ])

Why is the value within x1 also being updated here?

  • Assignment **does not** create a copy. – jonrsharpe Jan 08 '15 at 22:00
  • The "inadequate description" word you're looking for is "mutable". Most of the time "Python mutable list" will lead you there, but also numpy arrays. `x2` and `x1` point to the same thing: `x2` is not a full copy of `x1`: they refer to the same part of memory. For a proper copy, use `x2 = x1.copy()` for example. –  Jan 08 '15 at 22:01

1 Answers1

0

because of reference copies. You need to do more than just using = i.e. shallow copying.

Do this:

 x2 = numpy.copy(x1)

instead of using = sign. It is the same idea with C++/C shallow and deep copy principles.

ha9u63a7
  • 6,233
  • 16
  • 73
  • 108
  • Are you suggesting that `=` performs shallow copies? Because it does *not* do that. It simply increments the number of references *to the same object*. Really, in this case is about copying vs *not* copying, not how the copy is performed. – Bakuriu Jan 08 '15 at 22:03