1
import numpy as np

old_order=np.array([0,1,2,3,4,5,6,7,8])
new_order=old_order
swap_1,swap_2=random.sample(range(0,9),2)
new_order[swap_1],new_order[swap_2]=old_order[swap_2],old_order[swap_1]

print(old_order,new_order)

So I am trying to swap two random element within an array. old_order would be the original array and new_order would be the array after the switch happened. What I don't understand is that why would the values of the old_order be changed

enter image description here

I have narrow down the problem to

new_order[swap_1],new_order[swap_2]=old_order[swap_2],old_order[swap_1]

If this line is remove, both new order and old order will be the same.

2 Answers 2

2

There is only one array. old_order and new_order are both bound to the same array. This line

new_array = old_array

makes a new reference. It doesn't make a copy of the data. If you really need a copy, use old_order.copy().

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

1 Comment

Thank you so much, I have been scratching my head for like an hour
0
new_order=old_order.copy()

Create a new array for new_order. Otherwise new_order, old_order take the same memory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.