[Pythonmac-SIG] Mutating Row in a matrix

Bob Ippolito bob at redivi.com
Sat Jan 29 19:53:43 CET 2005


On Jan 29, 2005, at 1:29 PM, Kirk Durston wrote:

> It will be obvious that I am a newbie here when you see my question, 
> but here goes. I am writing my first program, and have encountered a 
> problem which I’ve been able to reproduce in the short program below. 
> Basically, I select a row (B) from a matrix and I want to keep B 
> constant. Then I create a new matrix by copying the old, and mutate 
> the new matrix. I then want to substitute the unmutated row B  into 
> the mutated new matrix.
>
> Problem: B changes, as you can see when you run the short program 
> below. So does the original matrix, although I don’t care about that.
>
> Question: Why does the list B change when I don’t work on it? I want 
> to understand this.
>
> Question #2: A solution would be to convert the list B into a tuple 
> and then reconvert the tuple back into a list after the new matrix has 
> been mutated and insert it, but I still want to understand why a list 
> would change when I’m haven’t done anything to it.

What you're missing here is that everything in Python is an object, and 
variables are just *references* to objects.  When you say ``a = b[0]``, 
``a`` is a reference to ``b[0]``.  If ``b[0]`` is some mutable object, 
like a list or a dict, you're simply referencing it.  In this case, 
changing ``a`` would "also change" ``b[0]`` because they ``a`` and 
``b[0]`` are references to the *same object*.

You should read this: 
http://starship.python.net/crew/mwh/hacks/objectthink.html

There is no need to convert a list to a tuple and back again.  Two 
simple ways to make a shallow copy of a list are ``list(anotherList)`` 
or ``anotherList[:]``.  You should also read the documentation for the 
``copy`` module, whether or not you end up using it in your 
implementation.

-bob



More information about the Pythonmac-SIG mailing list