Python - Sort Matrix by Maximum Row element

When you need to sort a matrix by the maximum element in each row, you can use Python's sort() method with a custom key function. This technique is useful for organizing data based on the highest value in each row.

Using a Custom Key Function

Define a function that returns the maximum element of each row, then use it as the sorting key ?

def sort_max(row):
    return max(row)

my_list = [[15, 27, 18], [39, 20, 13], [13, 15, 56], [43, 13, 25]]

print("The original matrix is:")
print(my_list)

my_list.sort(key=sort_max, reverse=True)

print("The sorted matrix is:")
print(my_list)
The original matrix is:
[[15, 27, 18], [39, 20, 13], [13, 15, 56], [43, 13, 25]]
The sorted matrix is:
[[13, 15, 56], [43, 13, 25], [39, 20, 13], [15, 27, 18]]

Using Lambda Function

You can also use a lambda function for a more concise approach ?

matrix = [[15, 27, 18], [39, 20, 13], [13, 15, 56], [43, 13, 25]]

print("Original matrix:")
print(matrix)

# Sort by maximum element in descending order
matrix.sort(key=lambda row: max(row), reverse=True)

print("Sorted matrix (descending by max element):")
print(matrix)
Original matrix:
[[15, 27, 18], [39, 20, 13], [13, 15, 56], [43, 13, 25]]
Sorted matrix (descending by max element):
[[13, 15, 56], [43, 13, 25], [39, 20, 13], [15, 27, 18]]

Ascending Order Sorting

To sort in ascending order, simply omit the reverse parameter or set it to False ?

matrix = [[15, 27, 18], [39, 20, 13], [13, 15, 56], [43, 13, 25]]

print("Original matrix:")
print(matrix)

# Sort by maximum element in ascending order
matrix.sort(key=lambda row: max(row))

print("Sorted matrix (ascending by max element):")
print(matrix)
Original matrix:
[[15, 27, 18], [39, 20, 13], [13, 15, 56], [43, 13, 25]]
Sorted matrix (ascending by max element):
[[15, 27, 18], [39, 20, 13], [43, 13, 25], [13, 15, 56]]

How It Works

  • The max() function finds the largest element in each row

  • The sort() method uses this maximum value as the sorting criterion

  • Setting reverse=True sorts in descending order (largest max values first)

  • The original matrix is modified in-place

Conclusion

Use sort(key=lambda row: max(row)) to sort a matrix by maximum row elements. Add reverse=True for descending order. This approach modifies the original matrix in-place.

Updated on: 2026-03-26T01:20:31+05:30

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements