Search code examples
pythondeep-copy

Problems with wrong values "return"-ed in Python ( a deep-copy issue )


I have defined the following function with Python:

def step(G,V1,V2):
    tempcut=sys.maxint
    for k in range(min(len(V1),len(V2))):
        V1, V2, C=Switch(G,V1,V2,k)
        print(C)
        if C<tempcut:
           tempcut=C
           best1=V1
           best2=V2
           print('enter')
           print(tempcut)
           print(best1)  
           print(best2)      
    return best1, best2, tempcut,  

G is a graph object (with networkx), V1 and V2 are two lists (a partition of the nodes of G). The function Switch(, , ) is another function that I've defined previously which returns an update of V1 and V2 and moreover an integer C.

My purpose is to return the lists best1, best2 and the smallest value of tempcut. The function returns the correct value of tempcut but on the other hand it returns the last values of V1 and V2, but not best1 and best2.


Solution

  • You should copy your list. You are changing it by reference. Check the official Python FAQ, Thread

    Try:

    import copy
    
    def step(G,V1,V2):
        tempcut=sys.maxint
        for k in range(min(len(V1),len(V2))):
            V1, V2, C=Switch(G,V1,V2,k)
            print(C)
            if C<tempcut:
               tempcut=C
               best1=copy.copy(V1) #or : best1= V1[:] as Serge suggested  
               best2=copy.copy(V2) #or : best2= V2[:] as Serge suggested  
               print('enter')
               print(tempcut)
               print(best1)  
               print(best2)      
        return best1, best2, tempcut,