Copying Double Arrays

This is the place for queries that don't fit in any of the other categories.

Copying Double Arrays

Postby mrotsliah » Wed Dec 11, 2013 9:20 pm

I have tried to simplify what what my basic problem is. I am doing more complicated things with double arrays.

Code: Select all

and the function

Code: Select all
def Checkk(W):
    return Q

Now, run the following code over and over:

print W
print Checkk(W)
print W

First run:


Second run:

[[1, 1]]
[[1, 1]]

Third run:

[[1, 1]]
[[1, 1, 1]]
[[1, 1, 1]]

Et cetera. It seems that W is changing each run. I was hoping the code Q=list(W) would copy the double array and leave W completely alone. I believe the code is copying the pointers to the inner array, but the inner array is shared by both Q and W.

I think Q=list(W) is just for single arrays. Is there a way to copy a double array in a similar fashion? I would like to modify Q and not have it also modify W.

Last edited by Yoriz on Wed Dec 11, 2013 9:27 pm, edited 1 time in total.
Reason: First post lock, Added code tags
Posts: 4
Joined: Wed Dec 11, 2013 8:49 pm

Re: Copying Double Arrays

Postby Yoriz » Wed Dec 11, 2013 9:27 pm

Hi welcome to the forum ive added code tags for you.
Please read the 'new user read this' link in my signature.
New Users, Read This
Join the #python-forum IRC channel on!
User avatar
Posts: 1628
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Copying Double Arrays

Postby micseydel » Wed Dec 11, 2013 9:35 pm

The different here is between shallow and deep copying. You're doing a shallow copy and you want a deep copy. You can get a deep copy by using the copy module (which you have to import) like so
Code: Select all
w_deep_copy = copy.deepcopy(w)
Join the #python-forum IRC channel on for off-topic chat!

Please prefer not to PM members. The point of the forum is so that anyone can benefit. We don't want to help you over PMs/emails/Skype chats that others can't benefit from :)
User avatar
Posts: 2906
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 5 guests