How to Find Length of Array in NumPy: Simple Guide
To find the length of a NumPy array, use the
len() function which returns the size of the first dimension. Alternatively, use array.size for total elements or array.shape to see all dimensions.Syntax
The main ways to find the length of a NumPy array are:
len(array): Returns the length of the first dimension (number of rows for 2D arrays).array.size: Returns the total number of elements in the array.array.shape: Returns a tuple showing the size of each dimension.
python
len(array)
array.size
array.shapeExample
This example shows how to find the length of a 1D and 2D NumPy array using len(), size, and shape.
python
import numpy as np # 1D array arr1 = np.array([10, 20, 30, 40]) print('Length of arr1:', len(arr1)) # 4 print('Total elements in arr1:', arr1.size) # 4 print('Shape of arr1:', arr1.shape) # (4,) # 2D array arr2 = np.array([[1, 2, 3], [4, 5, 6]]) print('Length of arr2:', len(arr2)) # 2 (number of rows) print('Total elements in arr2:', arr2.size) # 6 print('Shape of arr2:', arr2.shape) # (2, 3)
Output
Length of arr1: 4
Total elements in arr1: 4
Shape of arr1: (4,)
Length of arr2: 2
Total elements in arr2: 6
Shape of arr2: (2, 3)
Common Pitfalls
Many beginners expect len() to give the total number of elements in multi-dimensional arrays, but it only returns the size of the first dimension. To get total elements, use array.size. Also, array.shape helps understand the array's dimensions.
python
import numpy as np arr = np.array([[1, 2], [3, 4], [5, 6]]) # Wrong: expecting total elements wrong_length = len(arr) # returns 3, number of rows # Right: total elements correct_length = arr.size # returns 6 print(f'Wrong length (len): {wrong_length}') print(f'Correct total elements (size): {correct_length}')
Output
Wrong length (len): 3
Correct total elements (size): 6
Quick Reference
| Method | Description | Example Output |
|---|---|---|
| len(array) | Length of first dimension | len(np.array([[1,2],[3,4]])) โ 2 |
| array.size | Total number of elements | np.array([[1,2],[3,4]]).size โ 4 |
| array.shape | Tuple of dimensions | np.array([[1,2],[3,4]]).shape โ (2, 2) |
Key Takeaways
Use
len() to get the size of the first dimension of a NumPy array.Use
array.size to find the total number of elements in the array.Use
array.shape to understand the dimensions of the array.Remember that
len() does not give total elements for multi-dimensional arrays.Check array dimensions with
shape before deciding which length method to use.