The passed argument / parameter in the function still changes after deleting the link / alias

I spent the last 2 hours on this, and I probably read every question here regarding the passing of variables to functions. My problem is common to a parameter / argument that is affected by changes made inside the function, although I deleted the link / alias using variable_cloned = variable[:]the function to copy the content through without a link.

Here is the code:

def add_column(m):    
    #this should "clone" m without passing any reference on    
    m_cloned = m[:]
    for index, element in enumerate(m_cloned):
        # parameter m can be seen changing along with m_cloned even
        # though 'm' is not touched during this function except to 
        # pass it contents onto 'm_cloned'        
        print "This is parameter 'm' during the for loop...", m
        m_cloned[index] += [0]
    print "This is parameter 'm' at end of for loop...", m    
    print "This is variable 'm_cloned' at end of for loop...", m_cloned
    print "m_cloned is m =", m_cloned is m, "implies there is no reference"
    return m_cloned

matrix = [[3, 2], [5, 1], [4, 7]]
print "\n"
print "Variable 'matrix' before function:", matrix
print "\n"
add_column(matrix)
print "\n"
print "Variable 'matrix' after function:", matrix

What I noticed is that the "m" parameter in the function changes, as if it is an alias of m_cloned, but as far as I can tell, I deleted the alias with the first line of the function. Anywhere I looked online, it seems that this line will make sure that the link to the parameter is not specified, but it does not work.

, , , , 2 , .

+5
1

, , , [:]:

from copy import deepcopy
list2 = deepcopy(list1)

:

from copy import deepcopy

list1 = [[1], [1]]
list2 = list1[:]   # while id(list1) != id(list2), it items have the same id()s
list3 = deepcopy(list1)

list1[0] += [3]

print list1
print list2
print list3

:

[[1, 3], [1]]  # list1
[[1, 3], [1]]  # list2
[[1], [1]]     # list3 - unaffected by reference-madness
+9

All Articles