Skip to content
Laviyx Learn

Try

Python Lab · Experiment 23

Define a matrix and print it

PythonWeek 5JNTUH R22 · CS206ES

Aim

To write a Python program that defines a 3 × 3 matrix as a list of lists and prints it, first as a Python list and then in rows and columns.

Algorithm

  1. Define the matrix as a list of rows, where each row is a list of numbers.
  2. Find the number of rows with len(matrix) and the number of columns with len(matrix[0]).
  3. Print the matrix as it is stored, as a Python list.
  4. For each row index i, go through each column index j and print matrix[i][j] on the same line.
  5. After each row, move to a new line.
  6. Print one element by its row and column position to show how indexing works.

Program

Python
# A 3 x 3 matrix stored as a list of rows
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]

rows = len(matrix)
cols = len(matrix[0])
print("The matrix has", rows, "rows and", cols, "columns")

print("Matrix as a Python list:")
print(matrix)

print("Matrix in rows and columns:")
for i in range(rows):
    for j in range(cols):
        print(f"{matrix[i][j]:4}", end="")
    print()

print("Element in row 2, column 3 is", matrix[1][2])

Output

Output
The matrix has 3 rows and 3 columns
Matrix as a Python list:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Matrix in rows and columns:
   1   2   3
   4   5   6
   7   8   9
Element in row 2, column 3 is 6

Recorded by running this exact program.

How it works

Python has no separate matrix type in the core language. A matrix is usually stored as a list of lists: the outer list holds the rows, and each inner list holds the values of one row. matrix[i][j] is the value in row i and column j, counting from 0.

f"{value:4}" prints the value right-aligned in a field 4 characters wide, so the columns line up. end="" stops print from moving to a new line after each value.

The numpy library has a real array type for matrices, which you will meet in Week 8.

Common mistakes

  • Forgetting that indexes start at 0. The element in row 2, column 3 is matrix[1][2], not matrix[2][3] (which raises IndexError for a 3 × 3 matrix).

  • Leaving out the empty print() after the inner loop. Then every value comes out on one long line.

  • Creating a matrix with [[0] * 3] * 3. This makes three references to the same row, so changing one row changes all of them. Use [[0] * 3 for _ in range(3)] instead.

  • Using len(matrix) for the number of columns. That gives the number of rows; the number of columns is len(matrix[0]).

Viva questions

Try to answer each one aloud before you open it.

  • How is a matrix represented in Python without any library?

    As a list of lists. Each inner list is one row of the matrix.

  • How do you get the number of rows and columns of such a matrix?

    len(matrix) gives the number of rows and len(matrix[0]) gives the number of columns, assuming every row has the same length.

  • What does matrix[1][2] refer to?

    matrix[1] is the second row, and [2] picks its third value. For the matrix in this program it is 6.

  • What does end="" do in print?

    By default print ends with a newline. end="" replaces it with nothing, so the next print continues on the same line.

  • Why is [[0] * 3] * 3 a wrong way to create a 3 × 3 matrix?

    The outer * 3 copies the reference to the same inner list three times. All three rows are one list, so changing m[0][0] also changes m[1][0] and m[2][0].

Learn the concepts

All Python Programming Lab experiments →