 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Sort Matrix by Maximum String Length
When it is required to sort matrix by maximum string length, a method is defined that takes a list as parameter and uses list comprehension and the ‘max’ and ‘len’ methods to determine the result.
Below is a demonstration of the same −
Example
def max_length(row):    return max([len(element) for element in row]) my_matrix = [['pyt', 'fun'], ['python'], ['py', 'cool'], ['py', 'ea']] print("The matrix is :") print(my_matrix ) my_matrix .sort(key=max_length) print("The result is :") print(my_matrix )  Output
The matrix is : [['pyt', 'fun'], ['python'], ['py', 'cool'], ['py', 'ea']] The result is : [['py', 'ea'], ['pyt', 'fun'], ['py', 'cool'], ['python']]
Explanation
- A method named ‘max_length’ is defined that takes a list as a parameter, and gets the length of every element and uses ‘max’ to get the length of longest element. 
- Outside the method, a list of list is defined and is displayed on the console. 
- The list is sorted by specifying the method which was previously defined. 
- This is the output that is displayed on the console. 
Advertisements
 