Fundamentals 15 min read

Python List Comprehensions and Linear Algebra: From Simple Loops to Matrix Operations

This article demonstrates how Python’s expressive syntax—especially list comprehensions, dictionary and tuple comprehensions, and conditional expressions—can be used to implement fundamental linear‑algebra operations such as vector scaling, dot products, matrix transposition, projection, distance calculation, and even a one‑line linear solver, all illustrated with clear code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python List Comprehensions and Linear Algebra: From Simple Loops to Matrix Operations

When the author first started using Python, they missed libraries like NumPy and SymPy and wrote Pascal‑style loops, but soon discovered that Python’s friendly learning curve makes it possible to express rich linear‑algebra concepts with very few lines of code.

List Comprehension

Instead of a multi‑line loop that builds a list, a single‑line list comprehension can scale a vector:

def scaled(A, x): return [ai*x for ai in A]

List Compression

Multiple iterables can be zipped together and transformed in one comprehension, allowing concise vector addition:

def sum_of(A, B): return [ai+bi for (ai, bi) in zip(A, B)]

Python also supports dictionary and tuple comprehensions, e.g.:

{k:2*v for k, v in {0:1.0, 1:4.0, 2:3.0}.items()}
tuple(2*v for v in (1.0, 4.0, 3.0))

Conditional Expressions

Python’s ternary operator can build an identity matrix with a nested list comprehension:

def identity(n): return [[1.0 if i==j else 0.0 for j in range(n)] for i in range(n)]

Side‑effects can be introduced via tuple tricks, though they are discouraged:

def identity(n): return [[1.0 if i==j else (0.0, sys.stdout.write("i != j\n"))[0] for j in range(n)] for i in range(n)]

Passing Container Contents

Using the star operator to unpack a matrix for zip yields its transpose:

def transposed(A): return [list(col) for col in zip(*A)]

Matrix‑Vector Multiplication

A one‑line function computes the product of a matrix and a vector via the previously defined dot_of :

def matrix_vector_of(A, X): return [dot_of(row, X) for row in A]

Projection onto a Plane

Projecting a point onto a plane defined by a normal vector Pn and a point Pd uses scaling and summation helpers:

def projected_on(A, Pn, Pd): return sum_of(A, scaled(Pn, (Pd - dot_of(Pn, A)) / dot_of(Pn, Pn)))

Euclidean Distance

The distance between two points is obtained by subtracting, dot‑product, and square‑rooting:

def distance_between(A, B): return pow(dot_of(*(sum_of(A, scaled(B, -1.0)), ), 2), 0.5)

One‑Line Linear Solver

An iterative solver rotates the hyperplane by moving the first element to the end of the list until the solution is within a tolerance:

def solve(A, B, Xi):
    return Xi if distance_between(matrix_vector_of(A, Xi), B) < 1e-5 else solve(A[1:]+[A[0]], B[1:]+[B[0]], projected_on(Xi, A[0], B[0]))

Matrix Inversion (Conceptual)

By solving a linear system for each basis vector of the identity matrix, a matrix inverse can be expressed in a single line (though not the most efficient method):

def inverted(A): return transpose([solve(A, ort, [0.0]*len(A)) for ort in identity(len(A))])

Conclusion

With roughly ten lines of Python code the author demonstrates vector addition, scalar multiplication, dot product, matrix‑vector multiplication, identity matrix creation, transposition, inversion, projection, Euclidean distance, and a simple linear‑system solver, showcasing Python’s expressive power for mathematical programming.

pythoncode exampleslinear algebramatrix operationslist comprehensionEducational
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.