Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python shallow copy and deep copy in using append method

Some problems come out when using append method in python3.5. The code is presented

# generate boson basis in lexicographic order
def boson_basis(L,N):
basis=[]
state=[0 for i in range(1,L+1)]
pos=0
# initialize the state to |N,0,...,0>
state[0]=N
basis.append(state)
# find the first non-zero position in reverse order
while state[L-1]<N:
    for i in range(-2,-L-1,-1):
        if state[i]>0:
            pos=L+i
            break
    sum=0
    for i in range(0,pos):
        sum=sum+state[i]
    state[pos]=state[pos]-1
    state[pos+1]=N-sum-state[pos]
    basis.append(state)
return basis        

result=boson_basis(3,3)

the expected result should be [[3,0,0],[2,1,0],...,[0,0,3]], but this code generates wrong results with all elements are the same as the last one, i.e. [[0,0,3],...,[0,0,3]]. I use the pdb to debug it and I find that once the state is modified, the former state that has been appended into basis is also changed simultaneously. It implies that append uses deepcopy automatically which is beyond my understanding. In fact, this error can be fixed if we use basis(state.copy()) explicitly.

On the other hand, the following simple code shows no error in using append

x=3
b=[]
b.append(x)
x=x+2

after x is changed to x=5, b remains unchanged b=[3]. It really puzzles me and seems contradictory with the former example.

like image 383
AchillesJJ Avatar asked Nov 04 '16 14:11

AchillesJJ


People also ask

How do you use deep copy and shallow copy in Python?

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Does Python append make a copy?

💡 Tips: When you use . append() the original list is modified. The method does not create a copy of the list – it mutates the original list in memory.

How do you distinguish between copy copy () and copy Deepcopy () in Python?

copy() create reference to original object. If you change copied object - you change the original object. . deepcopy() creates new object and does real copying of original object to new one. Changing new deepcopied object doesn't affect original object.


1 Answers

As revealed in the comments already, there's no copy whatsoever involved in an append operation. So you'll have to explicitly take care of this yourself, e.g. by replacing

basis.append(state)

with

basis.append(state[:])

The slicing operation with : creates a copy of state. Mind: it does not copy the lists elements - which as long as you're keeping only plain numbers and not objects in your list should be fine though.

like image 113
sebastian Avatar answered Nov 02 '22 23:11

sebastian