Python array size: get size of array in Python

Python array size

In this article, we will see how to get size of array in Python.

Python array size

An array stores a collection of similar elements in a contiguous memory location. In Python, we have a list, an iterable, and a numpy array to work as arrays.

We can perform various operations on arrays. The array size tells how many elements are present in the array. We can use the size of the array to calculate how much memory the array occupies by multiplying the size of the array with the size of individual elements.

Ways to calculate the size of array in Python

Let us now discuss the different methods available to calculate the size of array in Python.

Using the len() function

The len() function returns the length of an iterable like a list, numpy array, or string.

For example,

Output:

4 3

In the above example, we initialized a numpy array and a list and returned their length using the len() function.

There is a drawback to this method. If we have a multi-dimensional array, it will not return the size of the array. It will consider every array within the outer array to be a single element and return that number.

We can understand this better with an example as shown below.

Output:

2 2

In the above example, we can see that the len() functions return the length as 2 and do not count the elements of the inner arrays.

Using the numpy.size() attribute

The numpy arrays have an attribute called numpy.size(), which can return the size of the given array. This function overcomes the drawback of multi-dimensional arrays in the len() function.

See the code below.

Output:

4
6

As you can see, the above code returns the size of a numpy array. This method is not compatible with lists. To make it work with lists, we can convert the list to a numpy array using the numpy.array() function.

Using the numpy.shape() attribute

The numpy.shape() attribute returns the shape of the numpy array, which can be considered as the number of rows and columns of an array. We get the shape in a tuple.

We can multiply the numbers in the tuple to get the size of the given array. This method also is limited to numpy arrays.

We implement the above logic in the following example.

Output:

4
6

In the above example,

  • The shape() attribute returns the shape of the given array.
  • The numpy.prod() function multiplies all the elements to return the size of the array.

Conclusion

In this article, we discussed several ways to get the size of array in Python. The most simple method is using the len() function, but it has its drawbacks and does not work with multidimensional arrays. The numpy.size() and numpy.shape() methods overcome this array but lack compatibility with lists.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *