# [Numpy-discussion] How to Keep An Array Two Dimensional

David Warde-Farley d.warde.farley at gmail.com
Mon Nov 26 01:07:13 EST 2012

```On Sun, Nov 25, 2012 at 9:47 PM, Tom Bennett <tom.bennett at mail.zyzhu.net> wrote:
> Thanks for the quick response.
>
> Ah, I see. There is a difference between A[:,:1] and A[:,0]. The former
> returns an Mx1 2D array whereas the latter returns an M element 1D array. I
> was using A[:,0] in the code but A[:,:1] in the example.

You'll notice that Python lists and tuples work the same way: foo[0]
on a list or tuple gives you the first element whereas foo[:1] gives
you a list or tuple containing only the first element.

To clarify what's going on in the case of NumPy: when you use the [:,
0] syntax, the interpreter is calling A.__getitem__ with the tuple
(slice(None), 0) as the argument. When you use [:, :1], the argument
is (slice(None), slice(None, 1)). You can try this out with
A[(slice(None), slice(None, 1))] -- it does the same thing (creating
index tuples explicitly like this can be very handy in certain cases).

The rule that NumPy follows for index tuples is (approximately) that
scalar indices always squash the corresponding dimension, whereas
slices or iterables (in the case of fancy indexing) preserve the
dimension with an appropriate size. Notably, A[:, [0]] will also
return an (A.shape[0], 1) array. But the semantics here are different:
because using a sequence as an "advanced" indexing operation, a copy
is made, whereas A[:, :1] will return a view.

Hope that makes things less mysterious,

David

```