Open In App

Find the number of rows and columns of a given matrix using NumPy

Last Updated : 20 Sep, 2025
Suggest changes
Share
3 Likes
Like
Report

In NumPy, determining dimensions of a matrix is a common task. Knowing number of rows and columns helps in data manipulation, analysis and reshaping operations.

Let's explore different methods to find the number of rows and columns of a matrix efficiently.

Using .shape Attribute

The .shape attribute of a NumPy array returns a tuple containing the number of rows and columns.

Example: In this example, we are finding rows and columns using .shape

Python
import numpy as np
m = np.array([[9, 9, 9], [8, 8, 8]])
rows, cols = m.shape

print("Rows:", rows)
print("Columns:", cols)

Output
('Rows:', 2)
('Columns:', 3)

Explanation:

  • np.array([[9, 9, 9], [8, 8, 8]]) creates a 2x3 matrix.
  • m.shape returns a tuple (2, 3).
  • Tuple unpacking rows, cols = m.shape assigns rows and columns to separate variables.

Using Indexing

One can find rows and columns by accessing the first and second elements of .shape. This is slightly less concise than direct unpacking.

Example: In this example, we are finding rows and columns using indexing

Python
import numpy as np
m = np.array([[4, 3, 2], [8, 7, 6]])

rows = m.shape[0]
cols = m.shape[1]

print("Rows:", rows)
print("Columns:", cols)

Output
('Rows:', 2)
('Columns:', 3)

Explanation:

  • .shape[0] gives the number of rows.
  • .shape[1] gives the number of columns.
  • Printing them shows Rows: 2 and Columns: 3.

Using numpy.reshape()

While reshape() is primarily used to change the shape of an array, it can also help to visualize dimensions by reshaping a 1D array into a 2D matrix. This method is less direct and generally slower than using .shape.

Example: In this example, we are finding rows and columns using reshape()

Python
import numpy as np
m = np.arange(1, 10).reshape((3, 3))
print(m)

rows, cols = m.shape
print("Rows:", rows)
print("Columns:", cols)

Output
[[1 2 3]
 [4 5 6]
 [7 8 9]]
('Rows:', 3)
('Columns:', 3)

Explanation:

  • np.arange(1, 10) creates a 1D array [1,2,3,4,5,6,7,8,9].
  • .reshape((3,3)) converts it into a 3x3 matrix.
  • .shape returns (3, 3), which is unpacked into rows and cols.

Explore