Python has a built-in function called len() that accepts a list and returns the total number of elements it contains.
even_arr = [2, 4, 6, 8, 10, 12] print("Length of a list:", len(even_arr)) # Length of a list: 6
The above example illustrates a list represented as an array, and we can clearly see 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
Finding an object’s size means determining the total number of elements in 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.
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 a single-dimensional array with a total of 6 elements. 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 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
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.