[Numpy-discussion] numarray iterator question

Robert Kern robert.kern at gmail.com
Wed Mar 10 19:22:40 EST 2010


On Wed, Mar 10, 2010 at 18:19, Neal Becker <ndbecker2 at gmail.com> wrote:
> This is a bit confusing to me:
>
> import numpy as np
>
> u = np.ones ((3,3))
>
> for u_row in u:
>    u_row = u_row * 2  << doesn't work
>
> print u
> [[ 1.  1.  1.]
>  [ 1.  1.  1.]
>  [ 1.  1.  1.]]
>
> for u_row in u:
>    u_row *= 2  << does work
> [[ 2.  2.  2.]
>  [ 2.  2.  2.]
>  [ 2.  2.  2.]]
>
> Naively, I'm thinking a *= b === a = a * b.

http://docs.python.org/reference/simple_stmts.html#augmented-assignment-statements

"""An augmented assignment expression like x += 1 can be rewritten as
x = x + 1 to achieve a similar, but not exactly equal effect. In the
augmented version, x is only evaluated once. Also, when possible, the
actual operation is performed in-place, meaning that rather than
creating a new object and assigning that to the target, the old object
is modified instead."""

> Is this behavior expected?  I'm asking because I really want:
>
> u_row = my_func (u_row)

Iterate over indices instead:

for i in range(len(u)):
    u[i] = my_func(u[i])

-- 
Robert Kern

"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 mailing list