-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?

9
  • 2
    B = A does not create a copy. Commented Oct 2, 2020 at 16:19
  • Correct, B just references the location in memory where A is stored, so they are pointing to the same thing. Commented Oct 2, 2020 at 16:20
  • I see. Is there a way to make a copy? Commented Oct 2, 2020 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: Explicit is better than Implicit. Commented Oct 2, 2020 at 16:22
  • 1
    @Yoddlenod read the following: nedbatchelder.com/text/names.html Commented Oct 2, 2020 at 16:32

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.