len() of a numpy array in python [duplicate]
Asked Answered
L

3

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?

Lecythus answered 28/3, 2017 at 23:43 Comment(2)
Just apply the len function over each row and run max over thatConfined
array.shape[i], with i indicating the relevant axis, should work well.Whoop
T
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).

Teasley answered 29/3, 2017 at 0:17 Comment(1)
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: mathworks.com/help/matlab/ref/length.html .)Karakul
B
11

Easy. Use .shape.

>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.
Barram answered 28/3, 2017 at 23:46 Comment(0)
C
-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)
Cornucopia answered 29/3, 2017 at 0:16 Comment(1)
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) > 2Grotto

© 2022 - 2024 — McMap. All rights reserved.