In Python, you can use the len()
function to determine the length of a NumPy array. However, the behavior of len()
depends on the shape of the array:
Using len()
on a NumPy Array
- The
len()
function returns the size of the first dimension (axis 0) of the array. - It does not consider the overall size or the length of other dimensions.
Example 1: One-Dimensional Array
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(len(arr)) # Output: 5
Example 2: Multi-Dimensional Array
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(len(arr)) # Output: 3 (number of rows in the first dimension)
Alternative Ways to Get Array Dimensions
- Number of Dimensions (
ndim
) Usearray.ndim
to get the number of dimensions.print(arr.ndim) # Output: 2
- Shape of the Array (
shape
) Usearray.shape
to get the size of all dimensions.print(arr.shape) # Output: (3, 3) for a 3x3 array
- Total Number of Elements (
size
) Usearray.size
to get the total number of elements.print(arr.size) # Output: 9
When to Use len()
vs. Other Methods
- Use
len()
when you need the size of the first dimension. - Use
.shape
,.ndim
, or.size
for more comprehensive information about the array.