2D Arrays In Python — PBA Institute Tutorial
Chapter 13 · Python Programming Series
12 min read Beginner

Working With 2D Arrays / Matrices

Whenever data has two dimensions — spreadsheets, images, game boards, matrices — a 2D array is the natural representation. Python supports two-dimensional structures via nested lists and, more powerfully, via the NumPy library. This chapter shows you both approaches with practical, real-world examples.

Overview

📊

Row × Column

Natural model for tables, grids, and matrices.

🧮

Math Ready

NumPy gives you transpose, multiply, invert, and more.

🖼️

Image Friendly

Greyscale images are 2D arrays of pixel intensities.

🎮

Game Boards

Tic-tac-toe, chess, Sudoku — all modelled as 2D arrays.

🗃️

Spreadsheet-Like

Read a CSV into rows × columns and process row by row.

Syntax

  • Nested list: matrix = [[1,2,3], [4,5,6], [7,8,9]].
  • Access an element with two indices: matrix[row][col].
  • Use NumPy: np.array(...) or np.zeros((rows, cols)) for true matrices.
  • Iterate row-by-row with nested loops, or use comprehensions for compact code.
2D Arrays / Matrices — Syntax
# Pure Python
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
print(grid[1][2])         # 6

# NumPy
import numpy as np
mat = np.array(grid)
print(mat.shape)          # (3, 3)
print(mat.T)              # transpose

Detailed Explanation

  • Definition: A 2D array organises data in rows and columns. Indexing requires two coordinates: row first, then column.
  • Nested lists: Pure Python uses lists of lists. Flexible but slower and less feature-rich than NumPy.
  • Initialising matrices: Use comprehensions for safety: [[0]*cols for _ in range(rows)]. Avoid [[0]*c]*r — it creates aliased rows!
  • Traversal: Nested loops over rows and columns: for i in range(rows): for j in range(cols): .... Or unpacked: for row in matrix: for val in row: ....
  • NumPy 2D arrays: np.array creates a real 2D array. Supports element-wise math, matrix multiplication (@), reshaping, and broadcasting.
  • Common operations: Transpose: mat.T. Sum across rows/columns: mat.sum(axis=0). Matrix multiplication: a @ b.

Code Examples

Example 1 — Create & Access
mat = [[1,2,3], [4,5,6], [7,8,9]]
print("center:", mat[1][1])
for row in mat:
    print(row)
Output center: 5
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Example 2 — Safe Initialisation
rows, cols = 3, 4
grid = [[0]*cols for _ in range(rows)]
grid[1][2] = 9
for r in grid:
    print(r)
Output [0, 0, 0, 0]
[0, 0, 9, 0]
[0, 0, 0, 0]
Example 3 — Sum of All Elements
mat = [[1,2,3], [4,5,6], [7,8,9]]
total = sum(v for row in mat for v in row)
print("Sum:", total)
Output Sum: 45
Example 4 — Transpose Using zip()
mat = [[1,2,3], [4,5,6]]
trans = [list(r) for r in zip(*mat)]
print(trans)
Output [[1, 4], [2, 5], [3, 6]]
Example 5 — NumPy Matrix Multiplication
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A @ B)
Output [[19 22]
 [43 50]]
Example 6 — Row & Column Sums
import numpy as np
m = np.array([[1,2,3], [4,5,6], [7,8,9]])
print("rows :", m.sum(axis=1))
print("cols :", m.sum(axis=0))
Output rows : [ 6 15 24]
cols : [12 15 18]

Real-World Use Cases

Spreadsheets

Excel/Google Sheets data loaded as a 2D structure.

Greyscale Images

Pixel intensities form a 2D matrix; colour adds a 3rd axis.

Board Games

Chess (8×8), Sudoku (9×9), Tic-tac-toe (3×3).

Pathfinding

Grid mazes used in A* / BFS algorithms.

Mark-sheets

Rows = students, columns = subjects, cell = score.

ML Feature Matrices

Rows = samples, columns = features.

Notes & Pro Tips

  • Always initialise matrices with comprehensions, never [[0]*c]*r.
  • Use NumPy when speed or math operations matter.
  • Use zip(*matrix) for an elegant transpose of nested lists.
  • Remember: matrix[row][col] — row first.
  • For sparse matrices (mostly zeros), use scipy.sparse instead.
  • Image libraries (PIL, OpenCV) all use NumPy 2D/3D arrays internally.

Common Mistakes

  • Aliased rows: [[0]*c]*r creates the same row r times.
  • Row/col mix-up: writing matrix[col][row] by mistake.
  • Ragged 2D lists: nested lists may have uneven lengths — validate first.
  • Treating Python list as matrix in math: use NumPy for matrix multiplication.
  • Forgetting axis argument: arr.sum() reduces everything; pass axis=0/1.
  • Indexing out of bounds: always check row and column counts before access.

Practice Problems

  • Problem 1: Print a 3×3 multiplication grid using nested for-loops.
  • Problem 2: Read a 2D matrix from the user and print its transpose.
  • Problem 3: Find the row with the maximum sum in a given matrix.
  • Problem 4: Check whether a matrix is a square matrix and symmetric.
  • Problem 5: Implement matrix addition without using NumPy.
  • Problem 6: Use NumPy to compute the determinant and inverse of a 3×3 matrix.

Interview Questions

  • Q1. What is a 2D array and how is it represented in Python?
  • Q2. Why is [[0]*c]*r dangerous?
  • Q3. How do you transpose a 2D list without NumPy?
  • Q4. What is matrix multiplication in NumPy and what operator does it use?
  • Q5. How do you sum elements along a row vs along a column in NumPy?
  • Q6. What is the difference between row-major and column-major order?

Frequently Asked Questions

  • Q1: How do I create a 2D array in Python?
    Use a list comprehension: [[0]*cols for _ in range(rows)] for pure Python, or np.zeros((rows, cols)) with NumPy.
  • Q2: How do I iterate over a 2D array?
    Two nested for-loops: for i in range(rows): for j in range(cols): grid[i][j]. Or for row in grid: for v in row: ...
  • Q3: How do I transpose a 2D list?
    List comprehension: [list(r) for r in zip(*matrix)]. With NumPy: arr.T.
  • Q4: Why use NumPy 2D arrays over nested lists?
    Memory layout is contiguous, math operations are vectorised, and many libraries expect ndarrays.
  • Q5: Can rows have different lengths?
    In nested lists, yes — but the result is ragged. NumPy arrays must be rectangular.
  • Q6: How do I find a value's position in a matrix?
    Loop with index pairs, or with NumPy use np.where(arr == target).

Summary

2D arrays organise data as rows and columns — the natural model for spreadsheets, images, boards, and matrices. Use nested lists for flexibility and NumPy for performance and math. Master indexing, traversal, and the few key operations like transpose, row/column sums, and matrix multiplication — and you'll be ready for everything from puzzle games to machine learning.

Continue Learning

Previous

Go to Previous Chapter

Next

Go to Next Chapter