Open In App

Python - Matrix creation of n*n

Last Updated : 28 Oct, 2025
Comments
Improve
Suggest changes
8 Likes
Like
Report

Given a number n, the task is to create an n × n matrix in Python. A matrix is a two-dimensional array where data is arranged in rows and columns.

For example:

n = 3
Matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

Let’s explore different methods to create an n×n matrix in Python.

Using NumPy Zeros

numpy.zeros() creates an n×n matrix filled with zeros. It’s highly optimized for performance and memory usage.

Python
import numpy as np
n = 4
m = np.zeros((n, n), dtype=int)
print(m)

Output
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

Using NumPy full() for Custom Values

numpy.full() allows creating an n×n matrix filled with any specific value. This is useful when initializing a matrix with a constant number.

Python
import numpy as np
n = 3
m = np.full((n, n), 5)
print(m)

Output
[[5 5 5]
 [5 5 5]
 [5 5 5]]

Using Nested List Comprehension

List comprehension is a concise way to create a matrix where each element is generated using a loop. It is suitable for creating matrices with uniform values or patterns.

Python
n = 4
m = [[0 for _ in range(n)] for _ in range(n)]
print(m)

Output
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Explanation: inner list comprehension creates columns, while the outer one creates rows, resulting in an n×n matrix.

Using Nested Loops

A nested loop allows more control over how each element of the matrix is generated, making this method ideal for generating custom matrices. It is mostly used when we have to generate dynamic or custom values for matrix elements.

Python
n = 3
m = []
count = 1

for i in range(n):
    row = []
    for j in range(n):
        row.append(count)
        count += 1
    m.append(row)

print(m)

Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Explanation: outer loop generates rows and the inner loop generates columns. Each element can be dynamically assigned, such as sequential numbers.


Explore