Python – Sort Matrix by total characters

When it is required to sort matrix by total characters, a method is defined that uses list comprehension and the ‘sum’ and ‘len’ methods to determine the result.

Below is a demonstration of the same −


 Live Demo

def total_characters(row):
   return sum([len(element) for element in row])

my_list = [["pyt", "is", "fun"], ["python", "fun"],["py", "4", "good"], ["python"]]

print("The list is :")


print("The result is :")


The list is :
[['pyt', 'is', 'fun'], ['python', 'fun'], ['py', '4', 'good'], ['python']]
The result is :
[['python'], ['py', '4', 'good'], ['pyt', 'is', 'fun'], ['python', 'fun']]


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

  • This is done by iterating over the elements using list comprehension and getting length of every element and adding these lengths.

  • Outside the method, a list is defined and displayed on the console.

  • The list is sorted and the method is called by passing the required parameter.

  • This result is assigned to a variable.

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