- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Matrix creation of n*n in Python
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
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.
Advertisements