Matrices in Python

Published: (April 5, 2026 at 02:05 PM EDT)
1 min read
Source: Dev.to

Source: Dev.to

Defining Matrices

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

Creating a 3x3 Matrix

matrix_3x3 = [[0]* 3 for in range(3)]

Common Matrix Problems

Transpose a Matrix

def calculate_transpose_of_matrix(mat: list[list]) -> list[list]:
    N = len(mat)
    for i in range(N):
        for j in range(i+1, N):
            mat[i][j], mat[j][i] = mat[j][i], mat[i][j]

    return mat
def print_matrix_in_spiral(mat: list[list]) -> list[list]:
    R = len(mat)
    C = len(mat[0])

    top = 0
    left = 0
    bottom = R - 1
    right = C - 1

    while top <= bottom and left <= right:
        for i in range(left, (right + 1)):
            print(mat[top][i], end=" ")
        top += 1
        for i in range(top, (bottom + 1)):
            print(mat[i][right], end=" ")
        right -= 1
        if top <= bottom:
            for i in range(right, (left - 1), -1):
                print(mat[bottom][i], end=" ")
            bottom -= 1
        if left <= right:
            for i in range(bottom, (top - 1), -1):
                print(mat[i][left], end= " ")
            left += 1
0 views
Back to Blog

Related posts

Read more »