0
0
NumpyHow-ToBeginner ยท 3 min read

How to Find Shape of Array in NumPy: Simple Guide

To find the shape of a NumPy array, use the .shape attribute. It returns a tuple showing the size of the array along each dimension.
๐Ÿ“

Syntax

The syntax to find the shape of a NumPy array is simple. Use array.shape, where array is your NumPy array.

  • array: Your NumPy array variable.
  • .shape: Attribute that returns a tuple with the size of each dimension.
python
array.shape
๐Ÿ’ป

Example

This example shows how to create a NumPy array and find its shape. The output is a tuple representing the number of rows and columns.

python
import numpy as np

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

# Find the shape of the array
shape = array.shape
print(shape)
Output
(3, 4)
โš ๏ธ

Common Pitfalls

One common mistake is trying to call shape as a function like array.shape(). Remember, shape is an attribute, not a method, so do not use parentheses.

Another pitfall is confusing the shape with the size. shape gives dimensions, while size gives total elements.

python
import numpy as np

array = np.array([1, 2, 3])

# Wrong: calling shape as a function
# print(array.shape())  # This will cause an error

# Right: access shape as attribute
print(array.shape)  # Output: (3,)
Output
(3,)
๐Ÿ“Š

Quick Reference

AttributeDescriptionExample Output
array.shapeReturns tuple of array dimensions(3, 4)
array.sizeReturns total number of elements12
array.ndimReturns number of dimensions2
โœ…

Key Takeaways

Use the .shape attribute to get the dimensions of a NumPy array.
Do not use parentheses with .shape because it is not a function.
The shape is a tuple showing size along each dimension.
For total elements, use .size instead of .shape.
Check .ndim to know how many dimensions the array has.