result = [] # final result
for i in range(len(A)):

    row = [] # the new row in new matrix
    for j in range(len(B[0])):
        
        product = 0 # the new element in the new row
        for v in range(len(A[i])):
            product += A[i][v] * B[v][j]
        row.append(product) # append sum of product into the new row
        
    result.append(row) # append the new row into the final result


print(result)
Answer from Aaron Shen on Stack Overflow
🌐
Programiz
programiz.com › python-programming › examples › multiply-matrix
Python Program to Multiply Two Matrices | Programiz
March 14, 2024 - In this program, we have used nested for loops to iterate through each row and each column. We accumulate the sum of products in the result. This technique is simple but computationally expensive as we increase the order of the matrix.
Discussions

How to perform Matrix Multiplication in Python - Stack Overflow
I have been trying to complete all matrix functions in python but i am stuck while multiplying 2 matrices. However , I can only get the last column to be added with one way and the diagonal element... More on stackoverflow.com
🌐 stackoverflow.com
Python Numpy matrix multiplication using loop to multiply multiple matrices together - Stack Overflow
Ty = matrix0 @ matrix1 @ matrix2 ... @ matrix9 · This works but the code has to be able to take multiple inputs with potentially more or fewer matrices being created. In that case it wouldn't work. Would it be possible to do the multiplication part using a loop or function? ... matrices = [] for i in ... More on stackoverflow.com
🌐 stackoverflow.com
Understanding nested matrix multiplication loops in Python
Length of X is the number of rows. Length of X[0] is the length of the first row, aka number of columns. More on reddit.com
🌐 r/learnpython
4
3
November 24, 2023
Beginning programming, Can someone explain why I need 3 for loops for matrix multiplication
I think you're confusing yourself about the concept of for loops. A programmer doesn't look at a problem and necessarily always think, "Oh, I need three for loops for this", although this does certainly become more natural over time. The process of knowing how many for loops you require to solve something tends to be more organic than that. Think about what a for loop is actually doing: Typically, you're using it to either count from one number to another, iterate over a set of values etc. So when someone knows they need to perform matrix multiplication, think about what you're actually doing: You need to multiply the rows of the first matrix with the columns on the second. This problem decomposes naturally into for loops: Let's say your result Matrix is called Matrix C. To get the first element of the first row of Matrix C, you need to multiply row 1 (r1) from your first Matrix, Matrix A, with column 1 (c1) from your second Matrix, Matrix B. To do this, you know that you need to look at each element of r1 and c1 (which have the same size). Thus, you need to iterate over them. This requires a for loop, so you can look at each element of r1 (and you can simultaneously use this loop to look at the corresponding element of c1), multiplying values and creating a sum. Now, with that single for loop, you have created the element in row 1, column 1 of Matrix C. But, you now need to create an element for every other position of Matrix C. This means you will need to iterate over all the possible positions inside Matrix C, repeating the for loop that I mentioned above each time. To do this, you will use one for loop to iterate over the rows of Matrix C, and one for loop nested inside this other for loop to iterate over the columns of Matrix C. Because your column for loop is nested inside your row for loop, you will iterate over every possible position in Matrix C. Think about it like this: Matrix C has 3 rows, 1 2 3. Matrix C has 3 columns, a b c. My first for loop will iterate over the rows, counting up, 1, 2, 3. My for loop inside the above for loop will iterate over the columns, counting up, a, b, c. Thus, when the row for loop has a value of 1, the column for loop will have values a, b, and c (meaning you can visit elements 1a, 1b and 1c of Matrix C). Then, the row for loop counts up to 2, and the column for loop repeats again, a, b, c (meaning you have now visited elements 2a, 2b, 2c). Finally, the row for loop increments to 3, and does all this again. Each time you visit a position in Matrix C (1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, and 3c), you are running a for loop that multiplies and sums elements from Matrix A and Matrix B, and puts it into that position. And there you go! Three for loops! More on reddit.com
🌐 r/compsci
24
23
June 21, 2013
Top answer
1 of 3
3

I have basically two comments:

  1. Naming.
  2. Use functions to follow the single responsibility principle.

Naming

Python has an official style-guide, PEP8. Some of its recommendations are:

  • Using lower_case for variables and functions, PascalCase for classes and ALL_CAPS for global constants.
  • To limit your line length to 80 (or at the most 120) characters

Your names which you use to iterate through the rows and columns are not clear at all. Why vc and vr (I guess the c and r stand for column and row, but what does the v stand for?)? Instead I would use rows and columns for the number of rows and columns and use i and j to iterate over them, because that is the convention used in mathematics when describing matrices.

Single responsibility principle

As for your actual code, you basically have four major responsibilities:

  1. Asking the user for input
  2. Creating a matrix
  3. Calculating the matrix product
  4. Printing a matrix scheme

I would make this into four functions:

def ask_user(message):
    while True:
        try:
            return int(input(message))
        except TypeError:
            pass

This function will ask the user the message until he inputs something that can be cast to an int.

def matrix_from_user():
    rows = ask_user("Number of rows?: ")
    columns = ask_user("Number of columns?: ")
    matrix = [[0] * columns for _ in range(rows)]
    for i in range(rows):
        for j in range(columns):
            matrix[i][j] = ask_user("M{}{}: ".format(i+1, j+1))
    return matrix

Here I used str.format to make the construction of the string easier.

def matrix_mul(matrix1, matrix2):
    rows, columns = len(matrix1), len(matrix2[0])
    matrix = [[0] * columns for _ in range(rows)]
    for i in range(rows):
        for j in range(columns):
            matrix[i][j] = sum(matrix1[i][k] * matrix2[k][j]
                               for k in range(len(matrix2)))
    return matrix

This is a straightforward implementation of the formula \ for two matrices \ and \. It uses the built-in sum function that takes an iterable to sum. This iterable is a generator comprehension here.

def matrix_print(matrix):
    print('\nElements of matrix:')
    rows, columns = len(matrix), len(matrix[0])
    for i in range(rows):
        row = ' '.join('M{}{}'.format(i + 1, j + 1) for j in range(columns))
        print('|', row, '|')

Here I used str.join to easily join an iterable of strings with a given delimiter (' ' here).

Your main program becomes then simply:

if __name__ == "__main__":
    matrix1 = matrix_from_user()
    matrix_print(matrix1)
    matrix2 = matrix_from_user()

    product = matrix_mul(matrix1, matrix2)

    print('Matrix1: ', matrix1)
    print('Matrix2: ', matrix2)
    print('Result of Matrix Multiplication:', product)

This code I put under an if __name__ == "__main__": guard which allows you to import this script from another script without this part of the code being run (so you get access to the functions).

2 of 3
2

For learning reason, you can create 2d array in one row like:

matrix2 = [[vc + v*10*vr  for vc in range(0, v)] for vr in range(0, r)]

Since python is a funcational language, for learning reason, you can define a map/ reduce over matrix like:

def map(matrix, r,c, fn,summ):
 for vr in range(0, r):                  
    for vc in range(0, c): 
       fn(matrix[r][c],summ)

or with additional map-reduce over the row:

  def map(matrix, r,c, fn,fnRow,startVal,summ):
     for vr in range(0, r):
        summRow = startVal
        for vc in range(0, c): 
           fn(matrix[r][c],summRow)
        fnRow(summRow, summ)

for learning reason you could implement Strassen matrix multiplication algorithm (google please), not naive one. I doubt you learn something like that.
For doing real project, use Numpy for initiations, not for high-performance operations.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-multiply-two-matrices
Python Program to Multiply Two Matrices - GeeksforGeeks
This method uses the classic three-loop approach: the outer loop picks a row from A, the middle loop picks a column from B, and the inner loop multiplies corresponding elements and adds them up.
Published: November 27, 2025
🌐
Geekflare
geekflare.com › development › 3 ways to multiply matrices in python
3 Ways to Multiply Matrices in Python
December 28, 2024 - The inner for loop helps us loop through the column of matrix B. And the innermost for loop helps access each element in the selected column. ▶️ Now that we’ve learned how the Python function to multiply matrices works, let’s call the function with the matrices A and B that we generated earlier.
🌐
Roadmap
roadmap.sh › python-data-analysis › matrix-multiplication
Matrix Multiplication in Python: The Complete Decision Guide
September 22, 2026 - While for loops offer a great way to learn about the inner workings of matrix multiplication, they produce relatively verbose code and aren’t the most efficient technique for multiplying large matrices. For an alternative pure Python approach that requires less code, you could try nested list comprehensions. This method computes the same output as the nested for loops, but is more Pythonic and does not require initialization of the result matrix. This is what the 2x2 matrix example looks like with nested list comprehensions.
🌐
OpenGenus
iq.opengenus.org › matrix-multiplication-in-python
Matrix Multiplication in Python (with and without Numpy)
April 11, 2023 - In this example, the matrix_mult method takes two matrices as arguments and performs matrix multiplication using nested loops. It first checks if the number of columns in the first matrix is equal to the number of rows in the second matrix, if not it returns "Cannot Multiply!" otherwise it ...
Find elsewhere
🌐
Geekboots
geekboots.com › home › python programming › matrix multiplication
Matrix Multiplication - Python | Geekboots
June 6, 2016 - #!/usr/bin/evn python # 3x3 matrix ... range(len(y[0])): # Iterate through rows of y for k in range(len(y)): mtMul[i][j] += x[i][k] * y[k][j] for mM in mtMul: print(mM) # ***** Output ***** # [40, 34, 28, 22] # [112, 97, 82, 67] ...
🌐
C# Corner
c-sharpcorner.com › home › technologies › python › matrix multiplication in python
Matrix Multiplication in Python
October 7, 2025 - A = [[1, 2, 3], [4, 5, 6]] B = ... logic for i in range(len(A)): for j in range(len(B[0])): for k in range(len(B)): result[i][j] += A[i][k] * B[k][j] for r in result: print(r) ... A = [[1, 2, 3], [4, 5, 6]] B = [[7, 8], [9, 10], [11, 12]] result = [[sum(a*b for a, b ...
🌐
Uncodemy
uncodemy.com › blog › matrix-multiplication-in-python-with-code
Matrix Multiplication in Python with Code | Learn with Examples
Q1. What’s the time complexity of matrix multiplication in Python? The basic method has a time complexity of O(m × n × p) because it involves three nested loops.
🌐
Vultr
docs.vultr.com › python › examples › multiply two matrices
Python Program to Multiply Two Matrices | Vultr Docs
December 26, 2024 - In these loops, i indexes rows of the first matrix, j indexes columns of the second matrix, and k iterates over the elements in the row of A and the column of B to compute each component of the product matrix.
🌐
Educative
educative.io › answers › how-to-multiply-matrices-in-python
How to multiply matrices in Python
Matrix multiplication is only possible ... in the form of a nested list ( a list inside a list ). ... In this, for loops are used to compute the resultant matrix....
🌐
Medium
medium.com › @asusrishabh › python-program-for-matrix-multiplication-5c1de08bb105
Python program for Matrix Multiplication | by Rishabh Singh | Medium
July 11, 2026 - def Multiply(A,B): result=[ [0,0,0],[0,0,0],[0,0,0] ] #for rows for i in range(len(A)): #for columns for j in range(len(B[0])): #for rows of matrix B for k in range(len(B)): result[i][j] += A[i][k] * B[k][j] for p in result: print(p) return ...
🌐
Medium
medium.com › @vtalladin06 › matrix-multiplication-in-python-without-libraries-a83b68819477
Matrix Multiplication in Python without libraries | by Tahseen Alladin | Medium
December 25, 2023 - Let’s try to understand the above code by taking an example. Let’s say we want to multiply two (2X2) Matrices. ... And we have initialised the result matrix with zeroes. We have done this, so that we can access the positions of this matrix by using its indices. This whole problem revolves around accessing the values through it’s indices. ... Note: Using Nested loops might seem complicated but if you just keep one thing in mind, then it gets a lot easier.
🌐
Leapcell
leapcell.io › blog › how-to-perform-matrix-multiplication-in-python
How to Perform Matrix Multiplication in Python | Leapcell
July 25, 2025 - This article will guide you through different ways to perform matrix multiplication in Python, from basic list comprehension to using powerful libraries like NumPy. Matrix multiplication is not the same as element-wise multiplication. To multiply two matrices A and B, the number of columns in A must match the number of rows in B. The resulting matrix C will have the same number of rows as A and the same number of columns as B. The most straightforward way to multiply two matrices is by using nested loops.
🌐
TutorialsPoint
tutorialspoint.com › article › python-program-multiplication-of-two-matrix
Python program multiplication of two matrix.
# Program to multiply two matrices def input_matrix(name): """Function to input a matrix from user""" n = int(input(f"Enter N for N x N matrix {name}: ")) matrix = [] print(f"Enter elements for matrix {name}:") for i in range(n): row = [] for j in range(n): element = int(input(f"Element [{i}][{j}]: ")) row.append(element) matrix.append(row) return matrix, n def display_matrix(matrix, name): """Function to display matrix in proper format""" print(f"Matrix {name}:") for row in matrix: for element in row: print(f"{element:3}", end=" ") print() def multiply_matrices(A, B, n): """Function to multip
🌐
Medium
medium.com › @stevenrouk › the-art-of-problem-solving-one-line-matrix-multiplication-list-comprehension-in-python-f65fbe01d1a9
The Art of Problem Solving: How to Create a One Line List Comprehension for Matrix Multiplication in Python | by Steven Rouk | Medium
August 26, 2019 - Well, matrix multiplication can be thought of as taking a row of A, a column of B, doing the dot product between them, and then storing that result in the new matrix. Specifically, if we take the 2nd row of matrix A and the 3rd column of matrix ...
🌐
Scaler
scaler.com › home › topics › python program to multiply two matrices
Python Program to Multiply Two Matrices - Scaler Topics
February 23, 2024 - This method encodes two matrices, ... C with zeros. Matrix multiplication is performed using nested loops, computing each element of C as the sum of products of corresponding elements from A and B....