Method # 1: Using an Comprehension List
Comprehension can be thought of as a shorthand for doing this particular operation. In a list comprehension, we can initialize an inner list and then extend that logic again to each line using a list comprehension.

Output:
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 comprehension list + operator "
*
"
This problem can also be simplified with the * operator, which can slightly reduce the time consuming way of doing the task and can just use the multiplication operator to extend the initialization to all N lines.
Output:
The matrix after initializing: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0]]
Shop
Latest questions
Wiki
# Python3 demo code
# initialization matrix
# using comprehension list
# and * operator
# Declaring Lines
N
=
5
# Column declarations
M
=
4
# using comprehension list
# to init matrix
res
=
[[
0
for
i
in
range
(M)]
*
N]
# print result
(
" The matrix after initializing: "
+
str
(res))