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
The list in Python works the same as an array in other programming languages, but numpy is a third-party library that specifically deals with numerical computations. Its basic type is “ndarray.“
Finding an object’s size simply means determining the total number of elements in its specific structure.
Python has a built-in function called len() that accepts a list and returns its total number of elements.
even_arr = [2, 4, 6, 8, 10, 12] print("Length of a list:", len(even_arr)) # Length of a list: 6
The above example is all about a list represented as an array, and we can clearly see that it has six elements.
Numpy array .size attribute
The NumPy array has a .size attribute that determines the length of 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.
Using len()
The len() function accepts a numpy array object and returns the length of the first dimension.
import numpy as np arr = np.array([2, 4, 6, 8, 10, 12]) print(len(arr)) # Output: 6
Here, we have only a single-dimensional array, and its total number of elements is 6. So, it returns 6.
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 totally different from the numpy module or built-in list data structure. You can use the len() function to find the array module’s array length.
import array arr = array.array('i', [11, 21, 19, 18]) print(len(arr)) # Output: 4
Conclusion
When dealing with a list or array module’s array data structure, use the len() function to find its size. If you are working with a numpy array, always use the .size attribute on the array object to get its size.