Python – Sort Matrix by Maximum String Length

When working with matrices (lists of lists) containing strings, you might need to sort rows based on the maximum string length in each row. Python provides an elegant solution using the sort() method with a custom key function.

Example

Here's how to sort a matrix by the maximum string length in each row ?

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)
The matrix is:
[['pyt', 'fun'], ['python'], ['py', 'cool'], ['py', 'ea']]
The result is:
[['py', 'ea'], ['pyt', 'fun'], ['py', 'cool'], ['python']]

How It Works

The sorting process follows these steps:

  • The max_length() function takes a row (list of strings) as parameter

  • It calculates the length of each string using list comprehension: [len(element) for element in row]

  • The max() function returns the longest string length in that row

  • The sort() method uses this function as the key to compare and order rows

Alternative Approach Using Lambda

You can achieve the same result using a lambda function ?

my_matrix = [['pyt', 'fun'], ['python'], ['py', 'cool'], ['py', 'ea']]

print("Original matrix:")
print(my_matrix)

my_matrix.sort(key=lambda row: max(len(element) for element in row))

print("Sorted matrix:")
print(my_matrix)
Original matrix:
[['pyt', 'fun'], ['python'], ['py', 'cool'], ['py', 'ea']]
Sorted matrix:
[['py', 'ea'], ['pyt', 'fun'], ['py', 'cool'], ['python']]

Sorting Analysis

Row Strings Max Length Sort Order
['py', 'ea'] 2, 2 2 1st
['pyt', 'fun'] 3, 3 3 2nd
['py', 'cool'] 2, 4 4 3rd
['python'] 6 6 4th

Conclusion

Use a custom key function with sort() to order matrix rows by maximum string length. The lambda approach provides a more concise solution for simple sorting criteria.

Updated on: 2026-03-26T01:04:20+05:30

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements