I’ve spent the last 2 hours on this and I’ve probably read every question on here relating to variables being passed to functions. My issue is the common one of the parameter/argument being affected by changes made inside the function, even though I have removed the reference/alias by using variable_cloned = variable[:] in the function to copy the contents across without the reference.
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's 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’m noticing is that the parameter ‘m’ in the function is changing as if is an alias of m_cloned – but as far as I can tell I have removed the alias with the first line of the function. Everywhere else I have looked online seems to suggest that this line will make sure there is no reference to parameter – but it’s not working.
I’m sure I must have made a simple mistake but after 2 hours I don’t think I’m going to find it.
It looks like you need a deepcopy, instead of a shallow copy, which is what
[:]gives you:Here’s a longer example comparing the two types of copy:
Outputs: