How To Create Matrix In Python

3 min read

How to Create Matrix in Python: The Ultimate Guide for Beginners and Developers

In the vast landscape of programming and data science, knowing how to create matrix in Python is a foundational skill that unlocks the door to linear algebra, machine learning, and complex data manipulation. A matrix is essentially a rectangular array of numbers arranged in rows and columns, serving as the backbone for representing images, datasets, and mathematical transformations. While Python does not have a built-in matrix data type in its standard library

While Python does not have a built-in matrix data type in its standard library, it offers three powerful approaches to handle matrix operations: native nested lists for simple scripting, the industry-standard NumPy library for high-performance numerical computing, and the array module for memory-efficient typed arrays. Choosing the right tool depends entirely on your use case—whether you are prototyping an algorithm, processing gigabytes of training data, or building a dependency-free utility script Worth knowing..


Method 1: Using Nested Lists (Pure Python)

For beginners or environments where installing external packages is restricted, a list of lists serves as the most intuitive representation of a matrix. Each inner list represents a row.

Basic Creation

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

# Accessing element at row 1, column 2 (0-indexed)
print(matrix[1][2])  # Output: 6

Dynamic Creation with List Comprehensions

Hardcoding values is impractical for large matrices. List comprehensions allow programmatic generation.

rows, cols = 4, 5

# Create a 4x5 matrix initialized with zeros
zero_matrix = [[0 for _ in range(cols)] for _ in range(rows)]

# Create an identity matrix (3x3)
n = 3
identity = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
# Result: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]

# Create matrix from a flat list (row-major order)
flat_data = list(range(1, 13)) # 1 to 12
matrix_3x4 = [flat_data[i*4:(i+1)*4] for i in range(3)]

⚠️ The Shallow Copy Trap

A common pitfall occurs when using the multiplication operator * to create rows Nothing fancy..

# WRONG: Creates 3 references to the SAME inner list
bad_matrix = [[0] * 3] * 3
bad_matrix[0][0] = 99
print(bad_matrix) 
# Output: [[99, 0, 0], [99, 0, 0], [99, 0, 0]] <- All rows changed!

# CORRECT: List comprehension creates distinct inner lists
good_matrix = [[0] * 3 for _ in range(3)]
good_matrix[0][0] = 99
print(good_matrix) 
# Output: [[99, 0, 0], [0, 0, 0], [0, 0, 0]]

Limitations

  • No native math: matrix_a + matrix_b concatenates lists; it does not perform element-wise addition.
  • Performance: Loops in pure Python are orders of magnitude slower than C-optimized libraries.
  • Memory overhead: Python objects carry significant overhead per integer/float.

Method 2: Using NumPy (The Industry Standard)

If you are doing data science, machine learning, scientific computing, or image processing, NumPy is non-negotiable. It provides the ndarray object—contiguous memory blocks with vectorized operations executed in C.

Installation

pip install numpy

Core Creation Routines

import numpy as np

# 1. From existing data (Lists/Tuples)
# dtype inference is automatic, but explicit is safer for production
A = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float64) 
print(A.shape) # (2, 3)

# 2. Special Matrices
zeros = np.zeros((3, 4))           # 3x4 zeros
ones = np.ones((2, 2), dtype=int)  # 2x2 integers
identity = np.eye(4)               # 4x4 Identity
diag = np.diag([1, 2, 3])          # Diagonal matrix from 1D array

# 3. Ranges and Sequences
arange = np.arange(0, 10, 2).reshape(2, 2) # [0, 2, 4, 6] -> 2x2
linspace = np.linspace(0, 1, 6).reshape(2, 3) # 6 even steps 0 to 1

# 4. Random Matrices (Crucial for ML weight initialization)
rng = np.random.default_rng(42) # Best practice: use Generator API
rand_uniform = rng.random((3, 3))        # Uniform [0, 1)
rand_normal = rng.standard_normal((3, 3)) # Standard Normal (mu=0, sigma=1)
rand_int = rng.integers(0, 10, size=(2, 5)) # Integers [0, 1
Newest Stuff

Recently Added

Explore a Little Wider

Still Curious?

Thank you for reading about How To Create 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