Home > Python > Matrix Operation

Ch. 4.6 Matrix using List Comprehension

Chapters Index
Program 1

Matrix using List Comprehension

Python 3.11 Ready

                                
Click "Run Code" to execute script and render figures.
Theoretical Principles & Computational Physics Guide

Matrix using List Comprehension: Pythonic Data Generation & Grid Creation

Dr. Alorika Chatterjee & Dr. Anirban Shaw Science & Physics Learners Python 3 / NumPy / SciPy

1. Core Principles & Theoretical Framework

Declarative Construction: Generates complex numerical arrays and spatial grids in clean, readable, single-line expressions.
Discretized Meshes: Ideal for building 2D spatial coordinate lattices $(x_i, y_j)$ for PDE solving and potential grids.
Avoiding Pointer Bugs: Prevents shallow copy bugs associated with multiplying lists ([[0]*n]*m creates linked row pointers!).

2. Mathematical Formulation & Algorithmic Pipeline

Discrete 2D mesh grid generation via Cartesian product:

$$ \mathbf{G}_{ij} = (x_0 + i\Delta x, \; y_0 + j\Delta y) \quad \forall i \in \{0,\dots,N_x-1\}, \; j \in \{0,\dots,N_y-1\} $$

3. Numerical Mechanics & Implementation Logic

  • Independent Row Instantiation: Use [[0 for j in range(cols)] for i in range(rows)] to ensure each row is an independent object.
  • Conditional Filtering: Embed boolean conditions to construct sparse or upper triangular matrices: [val if i <= j else 0 ...].
  • Functional Evaluation: Direct potential evaluation: [[potential(x[i], y[j]) for j in range(M)] for i in range(N)].

4. Relevant Computational Practice Exercises

Exercise 1
Construct a $5 \times 5$ Kronecker delta matrix $\delta_{ij}$ using a single nested list comprehension with an <code>if/else</code> condition.
Exercise 2
Generate a $10 \times 10$ 2D spatial grid representing gravitational potential $V(x, y) = -G / \sqrt{x^2 + y^2 + \epsilon^2}$.
Exercise 3
Demonstrate the shallow-copy pitfall of <code>[[0]*3]*3</code> when mutating a single element versus independent list comprehension.
Standard Literature & References:
  • Hans Petter Langtangen, "A Primer on Scientific Programming with Python", Springer (2016).