Pymatrix exports a lightweight, easy-to-use matrix object that supports all of Python's native numeric types, including integers, floats, and fractions (rational numbers).

Be warned that this library has been built for comfort, not for speed. Users with heavy-duty computational needs should turn to an optimised alternative like NumPy instead.


You can instantiate a matrix object directly, optionally specifying a fill value:

m = Matrix(rows, cols, fill=0)

You can instantiate a matrix object from a list of lists using the from_list() static method:

m = Matrix.from_list([
    [1, 2, 3],
    [4, 5, 6]

You can instantiate a matrix object from a string using the from_string() static method:

string = '''
1 2 3/7
4/7 5 6

m = Matrix.from_string(

Row separators default to newlines, column separators default to spaces. Leading and trailing whitespace is stripped from the string. Elements are parsed as fractions (rational numbers) by default.

You can instantiate an n x n identity matrix using the identity() static method:

m = Matrix.identity(n)

The shortcut matrix() function supports the syntax of all three static methods:

m = matrix([[1, 2, 3]])
m = matrix('1 2 3')
m = matrix(3)


Matrix objects are iterable. Iteration proceeds left-to-right by column, then top-to-bottom by row; i.e. the top-left element will be returned first, the bottom-right element will be returned last:

for element in matrix:

Alternatively, the elements() method returns an iterator over a tuple including row and column indices:

for row, col, element in matrix.elements():


Matrices are indexed as two-dimensional arrays:

matrix[row][col] = element

element = matrix[row][col]

Note that indices are zero-based in accordance with programming convention rather than one-based in typical math style, i.e. the matrix's top-left element is matrix[0][0] rather than matrix[1][1].

Matrix Methods

Matrix objects support the following methods:

Module Functions

The pymatrix module exports the following functions:


An invalid operation on a matrix object will raise a MatrixError exception.