NumPy ndarray.size Attribute



The NumPy ndarray.size attribute is used to get the total number of elements in a NumPy array. It returns an integer value representing the total count of elements, which is the product of the sizes of all dimensions of the array.

The size attribute is a simple and efficient way to determine the total number of elements in the array.

Usage of the size Attribute in NumPy

The size attribute can be accessed directly from a NumPy array object to find out how many elements the array contains.

It is commonly used when performing element-wise operations, reshaping arrays, or verifying the total number of elements in a multi-dimensional array.

Below are some examples that demonstrate how size can be applied to various arrays in NumPy.

Example: Basic Usage of size Attribute

In this example, we create a simple 1-dimensional array and use the size attribute to find out the total number of elements it contains −

import numpy as np

# Creating a 1-dimensional array
arr = np.array([1, 2, 3, 4])
print(arr.size)

Following is the output obtained −

4

Example: Checking the Size of a 2D Array

In this example, we create a 2-dimensional array and use the size attribute to determine the total number of elements −

import numpy as np

# Creating a 2-dimensional array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.size)

This will produce the following result −

6

Example: Size of a Higher Dimensional Array

In this example, we create a 3-dimensional array and use the size attribute to find the total number of elements −

import numpy as np

# Creating a 3-dimensional array
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr.size)

Following is the output of the above code −

8

Example: size with Empty Arrays

In the following example, we check the size of an empty array. This demonstrates that even an empty array has a defined size −

import numpy as np

# Creating an empty array
arr = np.array([])
print(arr.size)

The output obtained is as shown below −

0
numpy_array_attributes.htm
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy