Zed-King Institute

    Python Program to Add Two Matrices

    hardNested listsPython

    A matrix is a list of rows, and each row is a list of numbers — a nested list.

    The question

    The first line of input is n. The next n lines are the rows of matrix A, and the n lines after that are the rows of matrix B (numbers separated by spaces). Print A + B, one row per line, numbers separated by a single space.

    The code

    program.py

    n = int(input())
    A = [list(map(int, input().split())) for _ in range(n)]
    B = [list(map(int, input().split())) for _ in range(n)]
    for i in range(n):
        row = [A[i][j] + B[i][j] for j in range(n)]
        print(" ".join(map(str, row)))

    Input

    3
    1 10 2
    16 10 10
    4 6 12
    4 2 15
    10 16 18
    7 14 6

    Output

    5 12 17
    26 26 28
    11 20 18

    How it works

    1. 1Read n, then read n rows for A and n rows for B with a list comprehension.
    2. 2For every row i, build a new row where each element is A[i][j] + B[i][j].
    3. 3" ".join(map(str, row)) prints the row's numbers separated by single spaces.

    Common mistakes

    • Mixing up rows and columns: A[i][j] is row i, column j.
    • Printing the Python list itself, which shows brackets and commas instead of a matrix.

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions