[Numpy-discussion] linked variables?
Tue Jun 3 16:28:41 CDT 2008
On Tue, Jun 3, 2008 at 4:19 PM, Payton Gardner <firstname.lastname@example.org> wrote:
> Its probably something simple I don't understand but...
> I've written a dummy function which takes an array m. I'd like it to return
> a changed array m_i, and not change the initial array m. I call it with mm
> = dummy(m);
> 3 from numpy import *;
> 4 def dummy(m):
> 5 m_o = m;
> 6 pdb.set_trace();
> 7 m_step = 100;
> 8 m_i = m_o;
> 9 dummy = m;
> 10 dummy2 = m_o;
> 11 dummy3 = m_o;
> 12 i = 0;
> 13 m_i[i] = m_i[i] + m_step;
> 14 return(m_i);
> But after line 13 m, m_o, dummy, dummy2, and dummy3 are all changed by
> m_step, as well mm which is in a different name space. All I've asked it to
> do is change m_i. What's happening?
Python does not copy data when you assign something to a new variable.
Python simply points the new name to the same object. If you modify
the object using the new name, all of the other names pointing to that
object will see the changes. If you want a copy, you will need to
explicitly make one. For numpy arrays, the best way to do this is to
m_i = array(m_o)
"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
-- Umberto Eco
More information about the Numpy-discussion