To get the length of a Numpy array or Python list, an efficient way is to use the built-in len() function. It accepts an array or list and returns the total number of elements it contains.
import numpy as np even_arr = np.array([2, 4, 6, 8, 10, 12]) print(len(even_arr)) # Output: 6
The above example illustrates an array, and it is clear that it contains six elements.
When you want to get the size of an array, there are three possible contexts you are talking about:
- Size of a list
- Size of a numpy array
- Size of an array from the array module
Determining an object’s size involves calculating the total number of elements within its specific structure.
Numpy array .size attribute
The NumPy array has a .size attribute that determines the number of elements in an array. It returns the total number of elements of the array.
import numpy as np even_arr = np.array([2, 4, 6, 8, 10, 12]) print(even_arr.size) # Output: 6
What if I use the len() function on numpy arrays instead of the .size attribute? Let’s find out.
Multi-dimensional array
The problem arises when you start using multi-dimensional arrays.
Let’s say you have a 2D array like this: [[1, 2], [3, 4]], and you want to find its length.
If you pass this 2D array directly to the len() function, it will return two instead of 4. But why? The 2D array has 4 elements. Well, the first dimension’s length is two, which is an element [1, 2].
That’s why it returns 2 ((number of rows)). It does not return the total number of elements. It returns the length of the first dimension, which is 2.
import numpy as np np_2d_array = np.array([[1, 2], [3, 4]]) print(len(np_2d_array)) # Output: 2
That’s why it is better to use the .size attribute to find the total number of elements in the numpy array.
import numpy as np np_2d_array = np.array([[1, 2], [3, 4]]) print(np_2d_array.size) # Output: 4
Arrays from the array Module
Python also provides an “array” module, which is distinct from the NumPy module or the built-in list data structure. You can use the len() function to determine the length of an array.
import array
arr = array.array('i', [11, 21, 19, 18])
print(len(arr))
# Output: 4
That’s all!


