Python translating C saxpy
Question: This is the C code:

    
    
    btemp = (*beta)/(*beta_prev);
    for (k=0; k<xsize*ysize; k++) {
      parray[k] = zarray[k] + btemp*parray[k];
    }
    

And I am doing the following in Python:

    
    
    def saxpy(a, x, y):
        return np.array([a * xi + yi for xi, yi in zip(x, y)], np.float32)
    #...
    btemp = beta / beta_prev
    ptemp = saxpy(btemp, parray, zarray)
    parray[:] = ptemp
    

In my code, it seems to work fine (`zarray` and `parray` are changing
constantly because they are inside a while loop).

But then I do:

    
    
    btemp = beta / beta_prev
    parray = saxpy(btemp, parray, zarray)
    

My code fail after iterating a couple of time in the loop, are not they the
same?


Answer: You changed `parray[:] =` to just `parray =`, which is not equivalent. The
former assigns the content of `parray` on an elementwise basis, which is an
important distinction if `parray` is not of the same type as the right hand
side of the assignment.

Consider the two cases:

    
    
    >>> xs = [1, 2, 3, 4]
    >>> xs[:] = tuple(2 * x for x in xs)
    >>> xs
    [2, 4, 6, 8]
    >>> type(xs)
    <class 'list'>
    
    >>> xs = [1, 2, 3, 4]
    >>> xs = tuple(2 * x for x in xs)
    >>> xs
    (2, 4, 6, 8)
    >>> type(xs)
    <class 'tuple'>
    

