-3

Why is python sorting an array I'm not asking it to sort, and how do I get it to stop?

For example, I have an NumPy array A:

A = np.array[4, 7, 1, 3, 2], [3, 2, 4, 2, 1]

I wish to sort this array, but preserve its original structure so I can index it later. So my idea was to make a copy of the array and sort the copy:

B = A
B.sort()

Why is it then, that when I print A after this sort command, it prints the sorted array? Even though I never called sort on it?

print(a)


[[1 2 3 4 7]
[1 2 2 3 4]]

Is there a way around this?

Yoddlenod
  • 41
  • 8
  • 2
    `B = A` **does not** create a copy. – jonrsharpe Oct 02 '20 at 16:19
  • Correct, B just references the location in memory where A is stored, so they are pointing to the same thing. – whege Oct 02 '20 at 16:20
  • I see. Is there a way to make a copy? – Yoddlenod Oct 02 '20 at 16:22
  • See my answer below. – whege Oct 02 '20 at 16:22
  • 2
    @jonrsharpe I think that's a thing that's hard for people to wrap their head around with Python: `=` **never** makes a copy. If you want a copy, you have to be explicit about it. See [Zen of Python](https://www.python.org/dev/peps/pep-0020/): Explicit is better than Implicit. – Mark Ransom Oct 02 '20 at 16:22
  • @LiamFiddler I understand what you are saying, but talking about "referencing the same memory location where A is stored" is not a useful level of abstraction in Python. Python is a high-level language, there is no direct interaction with locations in memory or pointers. Names refer to objects. Assignment statements bind names to objects. `A = B` binds the object referenced by `B` to the name `A`. Consider an implementation of Python on the JVM, where objects aren't guaranteed to stay in the same location in the heap, then talking about "locations in memory" just becomes nonsensical – juanpa.arrivillaga Oct 02 '20 at 16:28
  • 1
    @Yoddlenod read the following: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Oct 02 '20 at 16:32
  • @juanpa.arrivillaga Do you have a link about objects not guaranteed to stay in the same location in the heap? Sounds interesting. – Kelly Bundy Oct 03 '20 at 00:27
  • @HeapOverflow it's nothing particularly crazy. The JVM, particularly the garbage collector, is free to move objects around, an in fact, it does. So here's a related question: https://stackoverflow.com/questions/1961146/memory-address-of-variables-in-java – juanpa.arrivillaga Oct 03 '20 at 03:34

1 Answers1

0

As mentioned above, B just points to the same location in memory as A, so modifying B also modifies A. You need to call the .copy() method, as shown below:

enter image description here

whege
  • 1,391
  • 1
  • 5
  • 13