LWZ
LWZ

Reputation: 12338

NumPy random.shuffle function

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?

Upvotes: 2

Views: 425

Answers (2)

zhangyangyu
zhangyangyu

Reputation: 8610

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

Upvotes: 1

falsetru
falsetru

Reputation: 368954

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.

Upvotes: 5

Related Questions