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.

Define
Code: Select all
W=[[]]

and the function

Code: Select all
def Checkk(W):
    Q=list(W)
    Q[0].append(1)
    return Q


Now, run the following code over and over:

print W
print Checkk(W)
print W

First run:

[[]]
[[1]]
[[1]]

Second run:

[[1]]
[[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.

Thanks
Last edited by Yoriz on Wed Dec 11, 2013 9:27 pm, edited 1 time in total.
Reason: First post lock, Added code tags
mrotsliah
 
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 irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 763
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 irc.freenode.net!
User avatar
micseydel
 
Posts: 1179
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot] and 4 guests