Explanation of list reference

Christian Gollwitzer auriocus at gmx.de
Sat Feb 15 10:38:22 CET 2014


Hi Dave,

Am 14.02.14 19:08, schrieb dave em:
> He is asking a question I am having trouble answering which is how a
> variable containing a value differs from a variable containing a list
> or more specifically a list reference.

as others have explained better and in more detail, there are mutable 
and immutable values. The point is, that in

	a=b

and

	a[1] = x

the "=" behaves differently. In the first case, you discard the 
reference, where a is pointing to, and bind to the same thing as b is 
pointing to. In the second case, you modify the thing that a is pointing 
to.

Recently, we tripped upon such a thing in a bad way; we were doing least 
squares fitting with numpy, and the parameters passed through were 
modified in the residuals function. That caused the LS algorithm to 
fail. After we got suspicious about this, we tried to remedy by copying 
the parameters

	param_copy = param[:]

It still didn't work, because a list behaves differently than a numpy 
array in this respect, to our big surprise:

# list slicing, as we know it
 >>> a=[1,2,3,4]
 >>> b=a[:] # list slicing creates a copy
 >>> b[1]=123
 >>> b
[1, 123, 3, 4]
 >>> a
[1, 2, 3, 4]

# now numpy array slicing
 >>> import numpy as np
 >>> a=np.array([1, 2, 3, 4])
 >>> a
array([1, 2, 3, 4])
 >>> b=a[:] # numpy slicing creates a reference
 >>> b[1]=123
 >>> b
array([  1, 123,   3,   4])
 >>> a
array([  1, 123,   3,   4])


Lesson learned: Don't modify parameters you got passed, if possible. It 
is rarely what you want and can sometimes even happen, when you know you 
don't want it.

	Christian



More information about the Python-list mailing list