0

I am wondering if someone can explain why Python modifies the original variable after assigning it to another variable and then passing the second variable the function call: Consider the following example code: Assume A is the original variable:

A=np.array(([1,20,30,40,10,5,60]))
B=A

B.sort()
print(A)
print(B)

The output for both is the same:

[ 1  5 10 20 30 40 60] 
[ 1  5 10 20 30 40 60]

A is the original variable and I assigned it the B and then I sort B, then why both A and B are sorted ? what if I want to sort B only and compare it to A

user59419
  • 893
  • 8
  • 20

1 Answers1

1

if you say B=A where A is an Array, Python just makes a new Pointer to A You can do

A = B[:]

to copy Array

eylion
  • 172
  • 10
  • "where A is an Array" irrelevant. The type of the object does not affect the semantics of assignment. All objects behave the exact same way. Also, `B[:]` **does not create a copy of a numpy array**. It create a *view*, so sorting the view will still sort the original. This behaves exactly the same way as the OP's code. – juanpa.arrivillaga Sep 22 '19 at 09:16
  • ups, you're right, that just applie to normal array. I never used numpy. But its not true that the type doesn't matter. integers, strings, floats ... get copied. Well its not just arrays that just get a new "pointer" or whatever, its all objects – eylion Sep 22 '19 at 09:31
  • should I edit the Answer or just delete because an answer is linked? – eylion Sep 22 '19 at 09:38