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?

3

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.