+

Initialize a matrix in Python

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.

# Python3 demo code
# initialization matrix
# using comprehension list

  
# Declaring lines

N = 5

 
# Column declarations

M = 4

  
# using comprehension list
# to initialize coding matrix

res = [[ 0 for i in range (N)] for j in range (M)]

 
# print result

print ( "The matrix after initializing:" + str (res))

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]]

Get Solution for free from DataCamp guru

# 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

print ( " The matrix after initializing: " + str (res))