# Python program to sort matrix based upon sum of rows

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

When it is required to sort matrix based upon sum of rows, a method is defined that uses ‘sum’ method to determine the result.

Below is a demonstration of the same −

## Example

Live Demo

def sort_sum(row):
return sum(row)

my_list = [[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]]

print("The list is :")
print(my_list)

my_list.sort(key = sort_sum)

print("The result is :")
print(my_list)

## Output

The list is :
[[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]]
The result is :
[[12, 41], [34, 51], [54, 36, 22], [32, 15, 67]]

## Explanation

• A method named ‘sort_sum’ is defined that takes a list as a parameter, and returns sum of the elements of the list as output.

• A list of list is defined and displayed on the console.

• The list is sorted using ‘sort’ method and the key is specified as the previously defined method.

• This is the output that is displayed on the console.

Updated on 06-Sep-2021 08:52:13