0
0
NumpyHow-ToBeginner ยท 3 min read

How to Find Size of Array in NumPy: Simple Guide

To find the size of a NumPy array, use the array.size attribute which returns the total number of elements. Alternatively, use numpy.size(array) function for the same result.
๐Ÿ“

Syntax

The size of a NumPy array can be found using either the size attribute or the numpy.size() function.

  • array.size: Returns the total number of elements in the array.
  • numpy.size(array): A function that returns the same total number of elements.
python
import numpy as np

# Using attribute
arr = np.array([1, 2, 3, 4])
print(arr.size)

# Using function
print(np.size(arr))
Output
4 4
๐Ÿ’ป

Example

This example shows how to find the size of arrays with different shapes using both methods.

python
import numpy as np

# 1D array
arr1 = np.array([10, 20, 30])
print('Size of arr1:', arr1.size)

# 2D array
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print('Size of arr2:', np.size(arr2))

# 3D array
arr3 = np.array([[[1], [2]], [[3], [4]]])
print('Size of arr3:', arr3.size)
Output
Size of arr1: 3 Size of arr2: 6 Size of arr3: 4
โš ๏ธ

Common Pitfalls

Some common mistakes when finding the size of a NumPy array include:

  • Confusing size with shape. size gives total elements, while shape gives dimensions.
  • Using len(array) which only returns the size of the first dimension, not total elements.
python
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

# Wrong: len() returns size of first dimension only
print('len(arr):', len(arr))  # Output: 2

# Correct: use size attribute
print('arr.size:', arr.size)  # Output: 6
Output
len(arr): 2 arr.size: 6
๐Ÿ“Š

Quick Reference

MethodDescriptionExample
array.sizeTotal number of elements in the arrayarr.size
numpy.size(array)Function to get total elementsnp.size(arr)
len(array)Length of first dimension only (not total size)len(arr)
โœ…

Key Takeaways

Use array.size to get the total number of elements in a NumPy array.
The numpy.size(array) function returns the same total element count.
Avoid using len(array) when you want total size; it only returns the first dimension length.
Remember size is total elements, while shape shows array dimensions.
Both attribute and function methods are simple and efficient for finding array size.