How to Print the Size of an Array in Python

In the world of programming, especially when dealing with data manipulation, manipulating and understanding the dimensions of arrays can be a crucial aspect. One such facet is finding the size of an array. In Python, this task is straightforward and easy. This tutorial will guide you on how to print the size of an array in Python.

Step 1: Import the Necessary Library

Before we can start working with arrays, we need to import the necessary libraries. In Python, the Numeric Python module commonly known as NumPy is used for a wide variety of mathematical and logical operations on arrays. Our first step is to import this library.

Step 2: Create an Array

Let’s now create a sample array for which we want to find the size. The size of an array is the total number of elements in the array.

Here, we have created a 1-dimensional array with 9 elements.

Step 3: Print the Size of Array

We use the size property of the NumPy array to get the size of the array. The size can be printed using the built-in function print().

The output from this code snippet should display:

9

This tells us that our array “my_array” has a total of 9 elements.

Step 4: Print the Size for the Multi-Dimensional Array

The previous steps only demonstrated printing the size of a 1-dimensional array. However, this process applies to multidimensional arrays too. Let’s create a 2-dimensional array and print its size:

The output from this code snippet should be:

9

Here, despite the array being 2-dimensional and comprising 3 arrays of 3 elements each, the total size of the array i.e., the total number of elements is still 9.

Final Python Script

Conclusion

In Python, the NumPy library allows for easy manipulation and analysis of arrays. In this tutorial, we learned how to quickly and easily print the size of an array in Python, which is a commonly used operation while working with data.

Whether you are working with a 1-dimensional or multi-dimensional array, Python and NumPy make it easy and efficient to find the total size of your array, thus allowing for better data manipulation and processing.