Find maximum and minimum value of a matrix

Jon_Computer picture Jon_Computer · May 1, 2014 · Viewed 17.6k times · Source

I have this code wrote in python 3:

matrix = []
    loop = True
    while loop:
        line = input()
        if not line: 
            loop = False
        values = line.split()
        row = [int(value) for value in values]
        matrix.append(row)

    print('\n'.join([' '.join(map(str, row)) for row in matrix]))
    print('matrix saved')

an example of returned matrix would be [[1,2,4],[8,9,0]].Im wondering of how I could find the maximum and minimum value of a matrix? I tried the max(matrix) and min(matrix) built-in function of python but it doesnt work.

Thanks for your help!

Answer

eugen picture eugen · Feb 10, 2020

One-liner:

for max:

matrix = [[1, 2, 4], [8, 9, 0]]
print (max(map(max, matrix))
9

for min:

print (min(map(min, matrix))
0