Change language

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

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method

# 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))