-4

What is the role of [:] in this program:

import numpy as np
l=np.array([[0,0,0,0],
            [4,5,6,7],
            [7,8,9,8]])
out[:]=np.nanstd(l, axis=0)
print(out)

If I write the third line of the code just like this (i.e., without [:]):

out=np.nanstd(l, axis=0)

I'd get the same result. So, what is the role of [:] and in what context does it make a difference?

user
  • 5,370
  • 8
  • 47
  • 75
math_enthusiast
  • 339
  • 2
  • 10
  • 1
    First of all, your code will raise a NameError, since `out` is not defined. Second, your "alternative" for the third line is the same as what you already put in your first example. – BrenBarn Dec 24 '16 at 08:47
  • @BernBarn I'm running the code in Jupyter and there is no error. I get the array of the result: [ 2.86744176 3.29983165 3.74165739 3.55902608]. And I edited the typo in the alternative. – math_enthusiast Dec 24 '16 at 08:52
  • That's a bad `duplicate` – hpaulj Dec 24 '16 at 16:57
  • Perhaps you've set up the `out` variable in your Jupyter setup, but otherwise, this can't run. The slicing syntax does make a difference, but without knowing more about `out`, no-one can't say. –  Dec 24 '16 at 17:11

1 Answers1

1

A Jupyter/ipython session maintains an Out dictionary that contains history. But Out[:] would give an error.

In a fresh session, this produces an error:

In [731]: out[:]=np.array([1,2,3])
....
NameError: name 'out' is not defined

But if I first create an out, the out[:] syntax works

In [732]: out=np.array([1,2,3])
In [733]: out
Out[733]: array([1, 2, 3])
In [734]: out[:]=np.array([4,5,6])
In [735]: out
Out[735]: array([4, 5, 6])

The first creates an out variable, in this case as an array. The second replaces the values in out with new ones. The number of values in the replacement will have to match the shape of the original.

If out is initially (or redefined as) a list, the [:] assignment also works, replacing all the values with new ones (which don't have to match).

In [736]: out=[1,2,3]
In [737]: out[:]=[4,5]
In [738]: out
Out[738]: [4, 5]

With a list out=... and out[:]=... are quite similar, and we'd have to look at the id(out) before and after to notice a difference.

But the basic point is out = ... assigns a new object to the variable. out[:] = ... assigns new values to an existing object. The exact action in the 2nd case depends on the class of that object.

hpaulj
  • 221,503
  • 14
  • 230
  • 353