Friday, January 17, 2025
HomeTechlen() of a numpy array in python

len() of a numpy array in python

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

  1. The len() function returns the size of the first dimension (axis 0) of the array.
  2. It does not consider the overall size or the length of other dimensions.
See also  R install packages from Shell

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

  1. Number of Dimensions (ndim) Use array.ndim to get the number of dimensions.
    print(arr.ndim)  # Output: 2
    
  2. Shape of the Array (shape) Use array.shape to get the size of all dimensions.
    print(arr.shape)  # Output: (3, 3) for a 3x3 array
    
  3. Total Number of Elements (size) Use array.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.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x