2

I ran into something strange with numpy.random.shuffle function

from numpy import arange
from numpy.random import shuffle

a = arange(5)
b = a
c = a[:]

shuffle(c)

a and b all changes with c. Actually no matter I shuffle() which variable, the other two all changes with it. I thought when I use slice copy the original variable should be independent. Did I miss something? How can I protect the original variable from being changed?

1
  • 1
    Using a slice makes a copy for ordinary lists, but not necessarily for all types. You have to read the documentation for any kind of object to use to see if slicing makes a copy or not. Commented Jul 14, 2013 at 7:27

2 Answers 2

5

According to the Basic slicing documentation:

All arrays generated by basic slicing are always views of the original array.

Use ndarray.copy or numpy.copy to get copy.

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

Comments

1

Using c = a.copy() can help you.

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.