15

If I use len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]])), I get back 3.

Why is there no argument for len() about which axis I want the length of in multidimensional arrays? This is alarming. Is there an alternative?

Monica Heddneck
  • 2,973
  • 10
  • 55
  • 89

3 Answers3

22

What is the len of the equivalent nested list?

len([[2,3,1,0], [2,3,1,0], [3,2,1,1]])

With the more general concept of shape, numpy developers choose to implement __len__ as the first dimension. Python maps len(obj) onto obj.__len__.

X.shape returns a tuple, which does have a len - which is the number of dimensions, X.ndim. X.shape[i] selects the ith dimension (a straight forward application of tuple indexing).

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • 3
    Beware that this is *not* the same behaviour as MATLAB. In MATLAB, the "length" of a multi-dimensional array is the length along the longest dimension (which could be calculated by `max(x.shape)` in Python). (See the docs: https://www.mathworks.com/help/matlab/ref/length.html .) – fonini Nov 16 '17 at 02:33
11

Easy. Use .shape.

>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.
Dmitry Pleshkov
  • 1,147
  • 1
  • 13
  • 24
-2

You can transpose the array if you want to get the length of the other dimension.

len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)
Batman
  • 8,571
  • 7
  • 41
  • 80
  • 3
    The reason this got negative votes is that it is a convoluted way to look at things. when applying `len`, you should get length, and shouldn't have to wonder about a mathematical identity to understand what len(transpose) represents. Also, this does not work for len(arr.shape) > 2 – Gulzar Aug 10 '19 at 13:06