Part of the series

Several example codes

~2 min read • Updated Sep 17, 2025

Program Overview

This Python program creates a 3×3 matrix and fills it with random integers between 0 and 20.
It then performs the following operations:
- Calculates and displays the total sum of all elements
- Calculates and displays the average of all elements
- Displays the maximum value in each row
- Displays the minimum value in each column


Python Code:


import random

# Create 3x3 matrix with random values between 0 and 20
matrix = [[random.randint(0, 20) for _ in range(3)] for _ in range(3)]

# Display the matrix
print("Matrix:")
for row in matrix:
    print(row)

# Sum and average of all elements
total_sum = sum(sum(row) for row in matrix)
average = total_sum / 9

print("\nTotal sum of elements:", total_sum)
print("Average of elements:", round(average, 2))

# Maximum of each row
print("\nMaximum value in each row:")
for i, row in enumerate(matrix):
    print(f"Row {i+1}: {max(row)}")

# Minimum of each column
print("\nMinimum value in each column:")
for col in range(3):
    column_values = [matrix[row][col] for row in range(3)]
    print(f"Column {col+1}: {min(column_values)}")

Sample Output:


Matrix:
[12, 3, 18]
[7, 0, 14]
[20, 5, 6]

Total sum of elements: 85
Average of elements: 9.44

Maximum value in each row:
Row 1: 18
Row 2: 14
Row 3: 20

Minimum value in each column:
Column 1: 7
Column 2: 0
Column 3: 6

Explanation:

Here’s how the program works:
- A 3×3 matrix is generated using nested list comprehensions and random.randint()
- The matrix is printed row by row
- The total sum is calculated using nested sum() calls
- The average is computed by dividing the total by 9
- Each row’s maximum is found using max()
- Each column’s minimum is found by extracting column values and applying min()


Written & researched by Dr. Shahin Siami