# Numpy-scalars vs Numpy 0-d arrays: copy or not copy?

Sebastien Bardeau Sebastien.Bardeau at obs.u-bordeaux1.fr
Fri Oct 20 04:42:26 CDT 2006

```Hi!

I am confused with Numpy behavior with its scalar or 0-d arrays objects:

>>> numpy.__version__
'1.0rc2'
>>> a = numpy.array((1,2,3))
>>> b = a[:2]
>>> b += 1
>>> b
array([2, 3])
>>> a
array([2, 3, 3])
>>> type(b)
<type 'numpy.ndarray'>

To this point all is ok for me: subarrays share (by default) memory with
their parent array. But:

>>> c = a[2]
>>> c += 1
>>> c
4
>>> a
array([2, 3, 3])
>>> type(c)
<type 'numpy.int32'>
>>> id(c)
169457808
>>> c += 1
>>> id(c)
169737448

That's really confusing, because slices (from __getslice__ method) are
not copies (they share memory), and items (single elements from
__getitem__ ) are copies to one of the scalar objects provided by Numpy.
I can understand that numpy.scalars do not provide inplace operations
(like Python standard scalars, they are immutable), so I'd like to use
0-d Numpy.ndarrays. But:

>>> d = numpy.array(a[2],copy=False)
>>> d += 1
>>> d
array(4)
>>> a
array([2, 3, 3])
>>> type(d)
<type 'numpy.ndarray'>
>>> d.shape
()
>>> id(d)
169621280
>>> d += 1
>>> id(d)
169621280

This is not a solution because d is a copy since construction time...
My question is: is there a way to get a single element of an array into
a 0-d array which shares memory with its parent array?

Sebastien

-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier