How To Write Matrix In Python

6 min read

A matrix is a rectangular arrangement of numbers, symbols, or expressions organized into rows and columns. So if you are just starting your journey in programming, learning how to write matrix in python is one of the most practical skills you can develop. Still, python does not have a built-in matrix type, but it offers flexible ways to create and manipulate matrices using native lists and powerful libraries like NumPy. Now, in programming, matrices are fundamental for representing data in fields such as machine learning, computer graphics, engineering, and scientific computing. This guide will walk you through every method, from simple list-based matrices to advanced numerical operations, so you can choose the right approach for your project.

What Is a Matrix in Python?

In mathematics, a matrix is a two-dimensional grid where each element is identified by its row and column index. In Python, you can think of a matrix as a collection of lists, where each inner list represents a row. To give you an idea, a 2x3 matrix has two rows and three columns:

matrix = [
    [1, 2, 3],
    [4, 5, 6]
]

Here, the element at row 0, column 1 is 2. Python uses zero-based indexing, so the first row is index 0 and the first column is also index 0. Understanding this structure is essential before you start writing matrix operations, because most errors in matrix programming come from mismatched dimensions or incorrect indexing.

Creating a Matrix Using Nested Lists

The simplest way to write matrix in python without installing any external library is to use nested lists. Now, a nested list is just a list inside another list. This method is ideal for small matrices, educational examples, and situations where you want to avoid external dependencies.

Basic Syntax

To create a matrix using nested lists, define a variable and assign it a list of lists:

# A 3x3 matrix
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

Each inner list must have the same number of elements to maintain a proper rectangular shape. If the inner lists have different lengths, you technically have a jagged array, which can cause problems during matrix operations The details matter here..

Accessing Elements

You can access individual elements using double indexing: matrix[row][column].

print(matrix[0][0])  # Output: 1
print(matrix[2][2])  # Output: 9

If you try to access an index that does not exist, Python will raise an IndexError, so always verify your matrix dimensions before accessing elements.

Modifying Elements

Nested lists are mutable, which means you can change specific values after creating the matrix:

matrix[1][1] = 99
print(matrix)
# Output: [[1, 2, 3], [4, 99, 6], [7, 8, 9]]

Adding Rows and Columns

You can add a new row using the append() method:

matrix.append([10, 11, 12])

To add a column, you must iterate through each row and append a value:

for row in matrix:
    row.append(0)

While nested lists work well for basic tasks, they become inefficient for large-scale numerical computations. This is where NumPy enters the picture.

Creating a Matrix Using NumPy

NumPy is the standard library for numerical computing in Python. Also, it provides a powerful ndarray object that is far more efficient than nested lists for matrix operations. If you plan to perform linear algebra, data analysis, or machine learning, you should write matrix in python using NumPy.

Installing NumPy

Before using NumPy, you need to install it. Open your terminal or command prompt and run:

pip install numpy

Once installed, import it in your Python script:

import numpy as np

Using np.array()

The most common way to create a NumPy matrix is by converting a nested list into a NumPy array:

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

NumPy arrays are homogeneous, meaning all elements must share the same data type. This constraint allows NumPy to store data in contiguous memory blocks, making operations significantly faster than with native Python lists It's one of those things that adds up. That's the whole idea..

Creating Special Matrices

NumPy includes built-in functions to generate commonly used matrices without manually typing every value.

Zeros matrix:

zeros = np.zeros((3, 3))

This creates a 3x3 matrix filled with zeros.

Ones matrix:

ones = np.ones((2, 4))

This creates a 2x4 matrix filled with ones.

Identity matrix:

identity = np.eye(4)

This creates a 4x4 identity matrix, where the diagonal elements are 1 and all other elements are 0.

Empty matrix:

empty = np.empty((2, 3))

This creates a 2x3 matrix with uninitialized values, which is

...not yet initialized and may contain arbitrary data from your system's memory Easy to understand, harder to ignore..

Generating Random Data and Reshaping Arrays

Beyond basic initialization, NumPy excels at generating random data and manipulating the structure of arrays without copying data unnecessarily Most people skip this — try not to..

To create a matrix filled with random integers, you can use the np.random module:

import numpy as np

# Random integers between 0 and 9
random_matrix = np.random.randint(0, 10, size=(3, 3))
print(random_matrix)

If you have a one-dimensional list and want to reshape it into a multi-dimensional matrix, NumPy makes it straightforward:

arr = np.arange(6)
matrix = arr.reshape((2, 3))
print(matrix)
# Output: [[0 1 2]
#          [3 4 5]]

Why Choose NumPy Over Native Lists?

While native Python lists are perfectly fine for storing small amounts of data or performing simple operations, they fall short when it comes

to numerical computing at scale. Native Python lists store references to objects scattered throughout memory, which creates overhead during iteration and arithmetic. NumPy, by contrast, stores homogeneous data in contiguous memory blocks and executes operations in optimized C code. This vectorization removes the need for explicit Python loops, often delivering speedups of orders of magnitude on large datasets.

Take this: adding two matrices with native lists requires nested loops or comprehensions:

# Native Python lists
result = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]

With NumPy, the same operation is a single, readable expression:

result = a + b

NumPy also supports broadcasting, which allows arithmetic between arrays of different compatible shapes, and it includes a comprehensive linear algebra module (np.linalg) for common tasks such as matrix multiplication, inversion, determinants, eigenvalues, and solving systems of linear equations.

# Matrix multiplication
product = a @ b   # equivalent to np.dot(a, b)

# Matrix inverse and determinant
inverse = np.linalg.inv(a)
determinant = np.linalg.det(a)

Memory efficiency is another major advantage. A NumPy array of one million integers consumes far less RAM than a Python list of the same integers, because it stores raw values rather than pointers to full Python objects.

Conclusion

Whether you are performing simple calculations, analyzing datasets, or building machine learning models, NumPy is the essential tool for how to write matrix in python. It combines the readability of Python with the performance of compiled code, offering everything from basic array creation and special matrices to random data generation and advanced linear algebra. By using NumPy’s vectorized operations and contiguous memory layout, you can focus on the mathematics of your problem instead of the mechanics of iteration. For any serious numerical work in Python, NumPy is not merely helpful—it is the standard.

New In

New on the Blog

Explore a Little Wider

We Picked These for You

Thank you for reading about How To Write Matrix In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home