NumPy ndarray.size

The numpy.ndarray.size attribute returns the total number of elements present in a NumPy array. It provides a quick way to determine the array’s size regardless of its shape or dimensionality.

Syntax

</>
Copy
ndarray.size

Return Value

AttributeTypeDescription
sizeintReturns the total number of elements in the array.

Examples

1. Getting the Size of a 1D Array

In this example, we create a 1D NumPy array and use the size attribute to determine the total number of elements.

</>
Copy
import numpy as np

# Creating a 1D NumPy array with 5 elements
arr = np.array([10, 20, 30, 40, 50])

# Getting the total number of elements in the array
size = arr.size
print("Number of elements in the array:", size)

Output:

Number of elements in the array: 5

2. Getting the Size of a 2D Array

Here, we create a 2D NumPy array and retrieve its total number of elements using the size attribute.

</>
Copy
import numpy as np

# Creating a 2D NumPy array (3 rows, 4 columns)
arr = np.array([[1, 2, 3, 4],
                [5, 6, 7, 8],
                [9, 10, 11, 12]])

# Getting the total number of elements in the 2D array
size = arr.size
print("Number of elements in the 2D array:", size)

Output:

Number of elements in the 2D array: 12

3. Getting the Size of a 3D Array

In this example, we create a 3D NumPy array and determine its total number of elements using the size attribute.

</>
Copy
import numpy as np

# Creating a 3D NumPy array (2 matrices of 2 rows and 3 columns each)
arr = np.array([[[1, 2, 3], [4, 5, 6]],
                [[7, 8, 9], [10, 11, 12]]])

# Getting the total number of elements in the 3D array
size = arr.size
print("Number of elements in the 3D array:", size)

Output:

Number of elements in the 3D array: 12

4. Verifying Size with Different Shapes

This example demonstrates how the size attribute remains consistent when the shape of an array is changed but the total number of elements remains the same.

</>
Copy
import numpy as np

# Creating a 1D NumPy array with 6 elements
arr = np.array([1, 2, 3, 4, 5, 6])

# Checking the size of the original array
print("Original array size:", arr.size)

# Reshaping into a 2D array (2 rows, 3 columns)
arr_reshaped = arr.reshape(2, 3)

# Checking the size after reshaping
print("Size after reshaping to 2D:", arr_reshaped.size)

# Reshaping into a 3D array (3 matrices of 1 row and 2 columns each)
arr_reshaped_3d = arr.reshape(3, 1, 2)

# Checking the size after reshaping to 3D
print("Size after reshaping to 3D:", arr_reshaped_3d.size)

Output:

Original array size: 6
Size after reshaping to 2D: 6
Size after reshaping to 3D: 6

As observed, even though the shape of the array changes, the size attribute remains the same, as it always represents the total number of elements in the array.