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
🌐
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
🌐
Programiz
programiz.com › python-programming › examples › multiply-matrix
Python Program to Multiply Two Matrices | Programiz
March 14, 2024 - Here are a couple of ways to implement matrix multiplication in Python. # Program to multiply two matrices using nested loops # 3x3 matrix X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] # result is 3x4 result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r)
🌐
OpenGenus
iq.opengenus.org › matrix-multiplication-in-python
Matrix Multiplication in Python (with and without Numpy)
April 11, 2023 - Matrix multiplication can be implemented in Python using nested for loops. The outer loop iterates through the rows of the first matrix, and the inner loop iterates through the columns of the second matrix.
🌐
HackerRank
hackerrank.com › challenges › map-reduce-advanced-matrix-multiplication › problem
Map Reduce Advanced - Matrix Multiplication | HackerRank
Currently, we provide the base code in Python. ... First line of the input will contain the number of test cases, for each test case, there will be two matrices. For each matrix, the first line will contain the number of rows and columns and ...
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.

Find elsewhere
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › hackerrank solution: martix script [python regex]
HackerRank Solution: Martix Script [Python Regex] | GoLinuxCloud
January 10, 2023 - It then transposes the matrix (converting the rows to columns and columns to rows) and creates a single string by concatenating all the characters in the transposed matrix. This string is then passed to a regular expression to replace any non-word and non-digit characters with spaces, and the modified string is printed. Now let us move toward a second possible solution using python nested for loop: ... import math import os import random import re import sys first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) m = int(first_multiple_input[1]) matrix = [] t = [] for i in range(n): matrix_item = [x for x in input()] matrix.append(matrix_item) for i in range(m): for j in range(n): t.append(matrix[j][i]) s = ''.join(t) path = re.compile(r'\b[ !@#$%&]+\b', re.M) k = re.sub(path, ' ', s) print(k)
🌐
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 - We’re currently figuring out how to do matrix multiplication using just built-in Python functions, and this isn’t a trivial task. After figuring this out using any approach we need (in this case, a for loop), we can then move on to crafting a solution that satisfies all of the requirements—namely, using a list comprehension.
🌐
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.
🌐
AlgoMonster
algo.monster › home › 311. sparse matrix multiplication
311. Sparse Matrix Multiplication - In-Depth Explanation
The space complexity is O(m × n), which is required to store the result matrix ans with dimensions m × n. The auxiliary space used by loop variables i, j, and k is O(1) and doesn't affect the overall space complexity. The biggest pitfall of this solution is that it doesn't take advantage of the sparse nature of the matrices. When matrices are sparse (containing mostly zeros), we're wasting significant computation time multiplying and adding zeros.
🌐
HackerRank
hackerrank.com › challenges › linear-algebra-foundations-4-matrix-multiplication › problem
Linear Algebra Foundations #4- Matrix Multiplication | HackerRank
Matrix Multiplication · Two matrices of size 3x3 are multiplied as shown below. Find the integers , , , , , , , , in the resultant matrix
🌐
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.
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › hackerrank solution: python loops [3 methods]
HackerRank Solution: Python Loops [3 Methods] | GoLinuxCloud
January 9, 2024 - This will also solve the problem: The only difference is that, instead of taking the power to find the square, this time we are multiplying the number by itself.
🌐
Medium
medium.com › @vtalladin06 › matrix-multiplication-in-python-without-libraries-a83b68819477
Matrix Multiplication in Python without libraries | by Tahseen Alladin | Medium
December 25, 2023 - 2. It reinforces your understanding of basic matrix operations, such as element-wise multiplication and summation, which are fundamental building blocks for more complex algorithms.
🌐
Medium
medium.com › @asusrishabh › python-program-for-matrix-multiplication-5c1de08bb105
Python program for Matrix Multiplication | by Rishabh Singh | Medium
July 11, 2026 - In this tutorial, we have learned three ways for multiplying the two matrices in Python. We have learned how to use nested loops, list comprehension, and the NumPy module in Python.
🌐
YouTube
youtube.com › whimsically mundane
DOT AND CROSS | HACKERRANK SOLUTION | NUMPY PYTHON | MATRIX MULTIPLICATION - YouTube
This video contains solution to HackerRank "Dot and Cross" problem. But remember...before looking at the solution you need to try the problem once for buildi...
Published: November 13, 2020
Views: 1K