Matrix creation of n*n in Python

When it is required to create a matrix of dimension n * n, a list comprehension is used. This technique allows us to generate a square matrix with sequential numbers efficiently.

Below is a demonstration of the same −

Example

N = 4
print("The value of N is")
print(N)

my_result = [list(range(1 + N * i, 1 + N * (i + 1)))
             for i in range(N)]

print("The matrix of dimension N * N is:")
print(my_result)

Output

The value of N is
4
The matrix of dimension N * N is:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

How It Works

The list comprehension creates each row by generating a range of consecutive numbers. For row i, it creates numbers from 1 + N * i to N * (i + 1):

  • Row 0: range(1, 5) ? [1, 2, 3, 4]

  • Row 1: range(5, 9) ? [5, 6, 7, 8]

  • Row 2: range(9, 13) ? [9, 10, 11, 12]

  • Row 3: range(13, 17) ? [13, 14, 15, 16]

Alternative Methods

Using Nested Loops

N = 3
matrix = []

for i in range(N):
    row = []
    for j in range(N):
        row.append(i * N + j + 1)
    matrix.append(row)

print("Matrix using nested loops:")
for row in matrix:
    print(row)
Matrix using nested loops:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Using NumPy

import numpy as np

N = 3
matrix = np.arange(1, N*N + 1).reshape(N, N)
print("Matrix using NumPy:")
print(matrix)
Matrix using NumPy:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Conclusion

List comprehension provides a concise way to create n*n matrices with sequential numbers. For larger matrices or mathematical operations, consider using NumPy for better performance and functionality.

Updated on: 2026-03-25T19:08:30+05:30

733 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements