0

In the following code, there is no reason I can see why variable "cleary" would change value, but it does. I have restarted pyCharm multiple times but it keeps happening.

import numpy as np

nPeriods = 48
nGens = 1
cleary = np.zeros((nPeriods,nGens,2))
clearz = np.zeros((nPeriods,nGens))

for ii in range(nPeriods):
    for jj in range(nGens):
        temp = cleary
        temp[ii,jj,:] = 1

What am I doing wrong?

Zanam
  • 4,607
  • 13
  • 67
  • 143
  • This is expected behavior. Check out the documentation – Nick Becker Sep 29 '16 at 17:36
  • Why do you expect that restarting your editor will change the core behavior of the Python language? – SethMMorton Sep 29 '16 at 17:37
  • Duplicate: [List changes unexpectedly after assignment. Why is this and how can I prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it) – Thomas Weller Mar 04 '22 at 12:00

1 Answers1

2

This is the expected behavior. You passed the reference of the ndarray object the name cleary is pointing to to temp when you did:

temp = cleary

You can avoid modifying cleary by assigning a copy of the array to temp:

temp = cleary.copy()

Read How do I pass a variable by reference? to learn more about the underpinnings of name assignments in Python.

Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139