0

Good afternoon!

The following is my snippet of code:

density_new = density_old[:,:,40:55]

for i in range(0,16):
    density_new[:,:,i] = 1020

Now, this should only change density_new, because by the way we allocate density_new it has its own memory ID (I double-checked using python's id() command on both variables). The problem is that when I run the code, it changes both density_old and density_new, and since they have different IDs, I don't know why this is happening. Any help would be appreciated.

2 Answers 2

1

Another solution:

import copy

density_new = copy.deepcopy(density_old[:,:,40:55])

From https://docs.python.org/2/library/copy.html :

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

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

Comments

0

when you copy a list to another one, python will make them refrence the same list so when updating one the other one automatically will be updated, but using list() function to copy a list will avoid this trick.

so just try this one:

density_new = list(density_old[:,:,40:55])

3 Comments

I did try this trick, but the issue is that now density_new is not an array, it's a list, and assigning values as in the for loop does not work. Since I use it as an array farther down for a variety of things, I need it to keep its structure. Is there a way to do that with list?
I'm not sure but you may use numpy arrays
Ah, got it, using np.asarray will convert it back to array form.

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.