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

python - Multiplication of any two matrices using lists and for in loop - Code Review Stack Exchange
I've just started learning Python and after few lessons I grasped the idea of lists and loop and decided to create my first project. Objective: Calculate multiplication of any two matrices from u... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
January 24, 2018
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
Python Matrix multiplication using for loop - Stack Overflow
0 Python Matrix Multiplication integers using for loops More on stackoverflow.com
🌐 stackoverflow.com
Python - Nested Loop Multiplication Matrix - Stack Overflow
This is equivalent to the double ... the matrix M. These are used everywhere in Python, so get used to them quickly! It's fairly easy to understand. For example, >>> [i for i in range(1,10)] [1, 2, 3, 4, 5, 6, 7, 8, 9] This is what the inner loop is doing, but then it multiplies those values ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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
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.

🌐
Geekflare
geekflare.com › development › 3 ways to multiply matrices in python
3 Ways to Multiply Matrices in Python
December 28, 2024 - How to write a custom Python function that checks if matrix multiplication is valid and returns the product matrix. The body of the function uses nested for loops.
🌐
Reddit
reddit.com › r/learnpython › understanding nested matrix multiplication loops in python
r/learnpython on Reddit: Understanding nested matrix multiplication loops in Python
November 24, 2023 -

Hi,

I have a problem in understanding nested python loops for matrix addition. For example:

X=[[1, 2, 3],[4, 5, 6], [7, 8, 9]]
for I in range(len(X)): 
    for j in range (len(X[0])): 
        r[i][j] = X[i][j] + Y[i][j]

I am able to understand length of X and that it represents the length of row but can't understand X[0]. Somebody please guide me.

Zulfi

🌐
Scaler
scaler.com › home › topics › python program to multiply two matrices
Python Program to Multiply Two Matrices - Scaler Topics
February 23, 2024 - Matrix multiplication is a binary operation on two matrices, which yields yet another matrix, which is referred to as the product matrix. The blog post covers four ways to multiply matrices in Python: nested loops, list comprehension, NumPy's vectorized functions, and a recursive approach.
Find elsewhere
🌐
OpenGenus
iq.opengenus.org › matrix-multiplication-in-python
Matrix Multiplication in Python (with and without Numpy)
April 11, 2023 - In this article, we will understand how to perform Matrix Multiplication in Python programming language. We have covered two approaches: one using Numpy library and other is a naive approach using for loop.
🌐
Leapcell
leapcell.io › blog › how-to-perform-matrix-multiplication-in-python
How to Perform Matrix Multiplication in Python | Leapcell
July 25, 2025 - To multiply two matrices A and ... of columns as B. The most straightforward way to multiply two matrices is by using nested loops....
🌐
Medium
medium.com › @aishahsofea › for-loops-vs-matrix-multiplication-ee67868f937
For-loops vs. Matrix Multiplication | by Aishah Sofea | Medium
June 2, 2020 - Then, we compute the dot product between the test data and the transposed train data to get the sum of multiplication between the two sets of data. Lastly, a set(or a matrix rather) of distances is calculated based on the derived formula.
🌐
Stack Overflow
stackoverflow.com › questions › 46385953 › python-nested-loop-multiplication-matrix
Python - Nested Loop Multiplication Matrix - Stack Overflow
For example, >>> [i for i in range(1,10)] [1, 2, 3, 4, 5, 6, 7, 8, 9] This is what the inner loop is doing, but then it multiplies those values by the row value for each row for the outer row.
🌐
C# Corner
c-sharpcorner.com › home › technologies › python › matrix multiplication in python
Matrix Multiplication in Python
October 7, 2025 - Matrix multiplication is a key skill in Python programming, especially for data processing and machine learning. While nested loops and list comprehensions are useful for understanding, NumPy provides the fastest and most reliable way to perform matrix operations in real-world scenarios.
🌐
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 ...
🌐
Geekboots
geekboots.com › home › python programming › matrix multiplication
Matrix Multiplication - Python | Geekboots
June 6, 2016 - #!/usr/bin/evn python # 3x3 matrix ... j in 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, ...
🌐
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 › @vtalladin06 › matrix-multiplication-in-python-without-libraries-a83b68819477
Matrix Multiplication in Python without libraries | by Tahseen Alladin | Medium
December 25, 2023 - 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. The inner loop must complete all it’s iterations before the outer loop can go for it’s next iteration. def multiply(matrix_a,matrix_b): # Initialize the result matrix with zeros result = [[0 for _ in range(len(matrix_b[0]))] for _ in range(len(matrix_a))] # Perform matrix multiplication for i in range(len(matrix_a)): for j in range(len(matrix_b[0])): for k in range(len(matrix_b)): result[i][j] += matrix_a[i][k] * matrix_b[k][j] return result