Matrix creation of n*n in Python

PythonServer Side ProgrammingProgramming

When it is required to create a matrix of dimension n * n, a list comprehension is used.

Below is a demonstration of the same −

Example

 Live Demo

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 * 0 is :")
print(my_result)

Output

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

Explanation

  • The value of N is predefined.

  • It is displayed on the console.

  • It tells about the dimensions of the matrix.

  • The number is iterated over, and is converted into a list.

  • This is assigned to a variable.

  • It is displayed on the console.

raja
Updated on 16-Apr-2021 12:12:23

Advertisements