Sometimes in the world of competitive programming, we need to initialise the matrix, but we don’t wish to do it in a longer way using a loop. We need a shorthand for this. This type of problem is quite common in dynamic programming domain. Let’s discuss certain ways in which this can be done.
Method #1 : Using List comprehension
List comprehension can be treated as a shorthand for performing this particular operation. In list comprehension, we can initialise the inner list and then extend this logic to each row again using the list comprehension.
The matrix after initializing : [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Method #2 : Using list comprehension + “
This problem can also be simplified using the * operator which can slightly reduce the tedious way task is done and can simply use multiply operator to extent the initialization to all N rows.
The matrix after initializing : [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Method #3 : Using + “
*” operator twice
Similar to above example we can also initialize the columns using “
*” operator twice.
The matrix after initializing : [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
- Python - Initialize dictionary keys with Matrix
- Python | Initialize common value to keys
- Python | Initialize tuples with parameters
- Python | Which is faster to initialize lists?
- Python | Initialize dictionary with None values
- Python | Initialize dictionary with common value
- Python - Initialize dictionary with custom value list
- Python | Initialize a dictionary with only keys from a list
- Python | Ways to initialize list with alphabets
- Python - Initialize empty array of given length
- Python | Initialize list with empty dictionaries
- Python | Initialize dictionary with multiple keys
- Python program to Convert a Matrix to Sparse Matrix
- Python - Convert Matrix to Custom Tuple Matrix
- How to initialize all the imported modules in PyGame?
- Python | Get Kth Column of Matrix
- Python | Numpy matrix.ptp()
- Python | Numpy matrix.take()
- Python | Row lengths in Matrix
- Python | Numpy matrix.mean()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Pushpak_Jalan