
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 −
Example
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(my_list) my_list.sort(key=total_characters) print("The result is :") print(my_list)
Output
The list is : [['pyt', 'is', 'fun'], ['python', 'fun'], ['py', '4', 'good'], ['python']] The result is : [['python'], ['py', '4', 'good'], ['pyt', 'is', 'fun'], ['python', 'fun']]
Explanation
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.
- Related Articles
- Python – Sort Tuples by Total digits
- Python – Sort Matrix by Row Median
- Python – Sort Matrix by None frequency
- Python – Sort Matrix by Palindrome count
- Sort Tuples by Total digits in Python
- Python – Sort Matrix by Maximum String Length
- Python - Sort Matrix by Maximum Row element
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Sort Characters By Frequency in C++
- Python Program to sort rows of a matrix by custom element count
- Python – Sort Matrix by Number of elements greater than its previous element
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- Python program to Sort a List of Strings by the Number of Unique Characters
- Column Sort of a Matrix in Python
- Python – Sort by range inclusion

Advertisements