Strange behavior related to value / reference

Chris Rebert clp2 at rebertia.com
Tue Oct 27 22:40:58 EDT 2009


On Tue, Oct 27, 2009 at 7:15 PM, Lambda <stephenhsu9 at gmail.com> wrote:
> I defined a function to raise a 2x2 matrix to nth power:
>
> def matrix_power(m, n):
>  result = m[:]

Note that this only copies the *outer* list. It does NOT copy any of
the inner, nested lists, it just makes fresh *references* to them,
which is what's causing your problem; the inner lists get shared, thus
the 2D lists are almost the same list for practical purposes.

You want:
result = [row[:] for row in m]
Which explicitly copies the inner lists.

<snip>
> I find the matrix and m lists are always equal.
> But these two lists are separate objects, right?

Right, but the *inner* list objects *are* the same in your code, and
lists with the same contents (in this case, the same inner lists)
compare as equal (==) but not identical (`is`). Remember that all
lists in Python are 1-dimensional; "multidimensional" lists are merely
by convention, hence you have to think a bit more carefully when
working with them.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list