- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Initialize Matrix in Python
In this article, we will learn about how we can initialize matrix using two dimensional list in Python 3.x. Or earlier.
Let’s see the intuitive way to initialize a matrix that only python language offers. Here we take advantage of List comprehension. we initialise the inner list and then extend to multiple rows using the list comprehension.
# input the number of rows N = 3 # input the number of columns M = 3 # initializing the matrix res = [ [ i*j for i in range(N) ] for j in range(M) ] # printing the matrix on screen row by row in a single line print("Inline representation:") [ [ print(res[i][j] ,end =" ") for i in range(N) ] for j in range(M) ] print("") # printing in multiple lines print("Multiline representation") for i in range(N): for j in range(M): print(res[i][j] ,end =" ") print("")
Inline representation: 0 0 0 0 1 2 0 2 4 Multiline representation 0 0 0 0 1 2 0 2 4
Now let's see the general way which can be implemented in any language. This is the standard way of creating a matrix or multidimensional-array
# input the number of rows N = 3 # input the number of columns M = 3 lis=[[0,0,0],[0,0,0],[0,0,0]] # initializing the matrix for i in range(N): for j in range(M): lis[i][j]=i # multiline representation for i in range(N): for j in range(M): print(lis[i][j],end=" ") print("")
0 0 0 0 1 2 0 2 4
In this article, we learned how to implement logic gates in Python 3.x. Or earlier. We also learned about two universal gates i.e. NAND and NOR gates.
- Initialize tuples with parameters in Python
- Initialize a window as maximized in Tkinter Python
- Python - Ways to initialize list with alphabets
- Python - Which is faster to initialize lists?
- Initialize HashSet in Java
- Initialize HashMap in Java
- Matrix manipulation in Python
- Rotate Matrix in Python
- Initialize an ArrayList in Java
- Transpose a matrix in Python?
- Spiral Matrix II in Python
- Set Matrix Zeroes in Python
- Custom length Matrix in Python
- Python – Convert Integer Matrix to String Matrix
- How to initialize variables in C#?