How to Represent a 2D Matrix in Python?

Estimated read time 2 min read

There are multiple ways to represent a 2D matrix in Python. Here are some common approaches:

  1. List of Lists: You can use a list of lists to represent a 2D matrix, where each inner list represents a row of the matrix. For example:
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

In this representation, matrix is a list containing three inner lists, each representing a row of the matrix. Accessing elements is done using indexing, such as matrix[row_index][column_index].

  1. Nested NumPy Array: If you have the NumPy library installed, you can use a NumPy array to represent a 2D matrix. NumPy provides additional functionalities for working with arrays efficiently. Here’s an example:
import numpy as np

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

In this case, matrix is a NumPy array representing a 2D matrix. Accessing elements can be done using indexing, similar to the list of lists representation.

  1. Dictionary of Tuples: Alternatively, you can use a dictionary of tuples to represent a 2D matrix, where each key-value pair represents a cell of the matrix. The keys can be tuples representing the row and column indices. Here’s an example:
matrix = {
    (0, 0): 1,
    (0, 1): 2,
    (0, 2): 3,
    (1, 0): 4,
    (1, 1): 5,
    (1, 2): 6,
    (2, 0): 7,
    (2, 1): 8,
    (2, 2): 9
}

In this representation, matrix is a dictionary where each key-value pair represents a cell of the matrix. Accessing elements can be done using indexing with tuples, such as matrix[(row_index, column_index)].

The choice of representation depends on your specific use case and the operations you plan to perform on the matrix. The list of lists representation is simple and widely used, while the NumPy array provides additional functionalities for numerical operations. The dictionary representation can be useful in specific scenarios where sparse matrices are involved or when you need to associate additional information with each cell.

Choose the representation that best suits your needs and adjust the matrix elements accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply