[Numpy-discussion] bug or feature?

Travis Oliphant oliphant@ee.byu....
Thu Feb 8 16:01:36 CST 2007

humufr@yahoo.fr wrote:

>I have a big problem with numpy, numarray and Numeric (all version)
>If I'm using the script at the bottom, I obtain these results:
>var1 before function is  [3 4 5]
>var2 before function is  1
>var1 after function must be [3 4 5] is  [ 9 12 15]     <------ problem
>var2 after function must be 1 is  1
>var3 must be the [9 12 15] is  [ 9 12 15]
>var4 must be the 'toto' is  toto
>I'm very surprised by the line noted. I always thinking that the input 
>variable didn't change the variable itself outside the function.
To save yourself confusion, you need to understand the difference 
between mutable and immutable types.  Mutable types can be changed 
inside of a function call.

You also need to understand that = is a "name-binding operation only"  
it does not change objects.

>Is it normal and so do I have to do a copy of the input data each time I'm 
>calling a function? 
Yes, it's very normal, if your function does an "in-place" operation on 
a mutable type.

Consider the following code:

def test(var1, var2):
      var1[0] *= 3  # this accesses the 0'th element of var1 and alters it.
      var2 = 'toto'  # this makes a new object and names it with var2
                            # whatever was passed in is gone
      return var1, var2


will return

[3,2,3], 'toto'


More information about the Numpy-discussion mailing list