0

It seems that the copy of a list is shuffled too?

So if I do for 2 lists:

data = examples
np.random.shuffle(examples)

then the list data is also shuffled? Why?

  • 1
    this is because python uses references for lists under the hood. This is more efficient in terms of memory usage. – LoW Feb 09 '21 at 07:51
  • This isn't a copy, it's an alias. – kaya3 Feb 09 '21 at 08:08
  • So, when do I know if I make an assignment with "=" python takes noth objects as an aliases?! Is this for all objects in python also for classes? I I want two seperate objects I have to use copy() or deepcopy()? –  Feb 09 '21 at 11:26

2 Answers2

1

Python doesn't create copies of objects when it thinks they're not needed.

In your case you can use built-in copy module:

import copy

data = copy.deepcopy(examples)
np.random.shuffle(examples)
The Godfather
  • 4,235
  • 4
  • 39
  • 61
0

You have to do examples = np.copy(data) because otherwise the two variables will reference the same position in memory meaning they both change.

Simon
  • 43
  • 8