Initialize Matrix in Python
Last Updated : 19 Feb, 2022
There are many ways to declare a 2 dimensional array with given number of rows and columns. Let us look at some of them and also at the small but tricky catches that accompany it.
We can do it using list comprehension, concatenation feature of * operator and few other ways.
Method 0: 2 list comprehensions
Python3
rows = 3 cols = 2 mat = [[ 0 for _ in range (cols)] for _ in range (rows)] print (f 'matrix of dimension {rows} x {cols} is {mat}' ) mat[ 0 ][ 0 ], mat[ 0 ][ 1 ] = 1 , 2 mat[ 1 ][ 0 ], mat[ 1 ][ 1 ] = 3 , 4 mat[ 2 ][ 0 ], mat[ 2 ][ 1 ] = 5 , 6 print (f 'modified matrix is {mat}' ) print (f 'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}' ) print (f 'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}' ) print (f 'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}' ) |
Output matrix of dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]] modified matrix is [[1, 2], [3, 4], [5, 6]] addr(mat[0][0]) = 11094304, addr(mat[0][1]) = 11094336 addr(mat[1][0]) = 11094368, addr(mat[1][1]) = 11094400 addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464
Method 1: 1 list comprehension inside and 1 concatenation operation outside
Python3
rows = 3 cols = 2 mat = [[ 0 for _ in range (cols)]] * rows print (f 'matrix with dimension {rows} x {cols} is {mat}' ) mat[ 0 ][ 0 ], mat[ 0 ][ 1 ] = 1 , 2 mat[ 1 ][ 0 ], mat[ 1 ][ 1 ] = 3 , 4 mat[ 2 ][ 0 ], mat[ 2 ][ 1 ] = 5 , 6 print (f 'modified matrix is {mat}' ) print (f 'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}' ) print (f 'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}' ) print (f 'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}' ) |
Output matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]] modified matrix is [[5, 6], [5, 6], [5, 6]] addr(mat[0][0]) = 11094432, addr(mat[0][1]) = 11094464 addr(mat[1][0]) = 11094432, addr(mat[1][1]) = 11094464 addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464
Method 2: 1 list comprehension outside and 1 concatenation operation inside
Python3
rows = 3 cols = 2 mat = [[ 0 ] * cols for _ in range (rows)] print (f 'matrix with dimension {rows} x {cols} is {mat}' ) mat[ 0 ][ 0 ], mat[ 0 ][ 1 ] = 1 , 2 mat[ 1 ][ 0 ], mat[ 1 ][ 1 ] = 3 , 4 mat[ 2 ][ 0 ], mat[ 2 ][ 1 ] = 5 , 6 print (f 'modified matrix is {mat}' ) print (f 'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}' ) print (f 'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}' ) print (f 'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}' ) |
Output matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]] modified matrix is [[1, 2], [3, 4], [5, 6]] addr(mat[0][0]) = 11094304, addr(mat[0][1]) = 11094336 addr(mat[1][0]) = 11094368, addr(mat[1][1]) = 11094400 addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464
Method 3: 2 concatenation operations
Python3
rows = 3 cols = 2 mat = [[ 0 ] * cols] * rows print (f 'matrix with dimension {rows} x {cols} is {mat}' ) mat[ 0 ][ 0 ], mat[ 0 ][ 1 ] = 1 , 2 mat[ 1 ][ 0 ], mat[ 1 ][ 1 ] = 3 , 4 mat[ 2 ][ 0 ], mat[ 2 ][ 1 ] = 5 , 6 print (f 'modified matrix is {mat}' ) print (f 'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}' ) print (f 'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}' ) print (f 'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}' ) |
Output matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]] modified matrix is [[5, 6], [5, 6], [5, 6]] addr(mat[0][0]) = 11094432, addr(mat[0][1]) = 11094464 addr(mat[1][0]) = 11094432, addr(mat[1][1]) = 11094464 addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464
Here we can see that output of Method 1 & Method 3 are *unexpected*.
We expected all rows in mat to be all different after we assigned them with 1,2,3,4,5,6 respectively. But in Method1 & Method3 they are all equal to [5,6]. This shows that essentially mat[0],mat[1] & mat[2] are all referencing the same memory which can further be seen by checking their addresses using the id function in python.
Hence be very careful while using (*) operator.
To understand it further we can use 3 dimensional arrays to and there we will have 2^3 possibilities of arranging list comprehension and concatenation operator. This is an exercise I leave for the reader to perform.
If working with numpy then we can do it using reshape method.
Python3
import numpy as np rows = 3 cols = 2 size = rows * cols mat = np.array([ 0 ] * size).reshape(rows,cols) |
Similar Reads
Python - K Matrix Initialization
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
5 min read
Python - Initialize dictionary keys with Matrix
Sometimes, while working with Python Data, we can have a problem in which we need to construct an empty mesh of dictionaries for further population of data. This problem can have applications in many domains which include data manipulation. Let's discuss certain ways in which this task can be perfor
4 min read
Python Initialize List of Lists
A list of lists in Python is often used to represent multidimensional data such as rows and columns of a matrix. Initializing a list of lists can be done in several ways each suited to specific requirements such as fixed-size lists or dynamic lists. Let's explore the most efficient and commonly used
3 min read
Boolean list initialization - Python
We are given a task to initialize a list of boolean values in Python. A boolean list contains elements that are either True or False. Let's explore several ways to initialize a boolean list in Python. Using List MultiplicationThe most efficient way to initialize a boolean list with identical values
3 min read
Python | Row lengths in Matrix
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the lengths of rows of matrix in uneven sized matrix. Let's discuss certain ways in which this problem can be solved. Method #1 : Using max() + m
4 min read
Python - Incremental Range Initialization in Matrix
Sometimes, while working with Python, we can have a problem in which we need to perform the initialization of Matrix. Simpler initialization is easier. But sometimes, we need to perform range incremental initialization. Let's discuss certain ways in which this task can be performed. Method #1: Using
4 min read
Python - Incremental K sized Row Matrix Initialization
Sometimes, while working with Python, we can have a problem in which we need to perform initialization of matrix with Incremental numbers. This kind of application can come in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + list slicing Th
6 min read
Python - Convert Matrix to Dictionary
The task of converting a matrix to a dictionary in Python involves transforming a 2D list or matrix into a dictionary, where each key represents a row number and the corresponding value is the row itself. For example, given a matrix li = [[5, 6, 7], [8, 3, 2], [8, 2, 1]], the goal is to convert it i
4 min read
Python | Custom length Matrix
Sometimes, we need to initialize a matrix in Python of variable length from the list containing elements. In this article, we will discuss the variable length method initialization and certain shorthands to do so. Let's discuss certain ways to perform this. Method #1: Using zip() + list comprehensio
6 min read
How to Initialize a String in Python
In Python, initializing a string variable is straightforward and can be done in several ways. Strings in Python are immutable sequences of characters enclosed in either single quotes, double quotes or triple quotes. Letâs explore how to efficiently initialize string variables. Using Single or Double
2 min read