Dremendo Tag Line

Input numbers in nested list and swap the largest with the smallest number in Python

Lists - Question 9

In this question, we will see how to input numbers in a 3X3 integer matrix (nested list) and interchange the largest with the smallest number from it in Python programming. To know more about lists click on the lists lesson.

Q9) Write a program in Python to input numbers in a 3X3 integer matrix (nested list) and interchange the largest with the smallest number from it.

Program

a=[[],[],[]]
r=0;c=0;lg=0;lr=0;lc=0;sm=0;sr=0;sc=0

print('Enter 9 numbers')
for r in range(3):
    for c in range(3):
        a[r].append(int(input()))
        if r==0 and c==0:
            lg=a[r][c]
            lr=r
            lc=c
            sm=a[r][c];
            sr=r
            sc=c
        elif a[r][c]>lg:
            lg=a[r][c]
            lr=r
            lc=c
        elif a[r][c]<sm:
            sm=a[r][c]
            sr=r
            sc=c

a[lr][lc]=sm
a[sr][sc]=lg

print('\nMatrix after interchanging largest with the smallest number');
for r in range(3):
    for c in range(3):
        print(a[r][c],end=' ')
    print()

Output

Enter 9 numbers
5
12
18
2
17
23
45
96
62

Matrix after interchanging largest with the smallest number
5 12 18
96 17 23
45 2 62
video-poster