# Python â€“ Sort Matrix by Row Median

When it is required to sort matrix by row median, a method is defined that uses the ‘median’ method to determine the result.

Below is a demonstration of the same −

## Example

Live Demo

from statistics import median

def median_row(row):
return median(row)

my_list = [[43, 14, 27], [13, 27, 24], [32, 56, 18], [34, 62, 55]]

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

my_list.sort(key = median_row)

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

## Output

The list is :
[[43, 14, 27], [13, 27, 24], [32, 56, 18], [34, 62, 55]]
The result is :
[[13, 27, 24], [43, 14, 27], [32, 56, 18], [34, 62, 55]]

## Explanation

• The required packages are imported into the environment.

• A method named ‘median_row’ is defined that takes row as a parameter, returns median of the row as output using ‘median’ method.

• 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.