
- 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 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.
- Related Articles
- Python - Sort Matrix by Maximum Row element
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Python – Sort Matrix by total characters
- Python – Sort Matrix by Row Median
- Python – Sort Matrix by None frequency
- Python – Sort Matrix by Palindrome count
- Python – Sort by Maximum digit in Element
- Find maximum path length in a binary matrix in Python
- Python program to Sort Tuples by their Maximum element
- What is the maximum length of string in Python?
- Python – Sort String list by K character frequency
- Sort by character length in MySQL
- Python Program to sort rows of a matrix by custom element count
- Python – Sort Matrix by Number of elements greater than its previous element
- Custom length Matrix in Python

Advertisements