Python – Sort Matrix by None frequency

When it is required to sort a matrix by None frequency, we can define a helper function that counts None values in each row using list comprehension and the not operator. The matrix is then sorted based on the count of None values in ascending order.

Example

Below is a demonstration of sorting a matrix by None frequency ?

def get_None_freq(row):
    return len([element for element in row if not element])

my_list = [[None, 24], [None, 33, 3, None], [42, 24, 55], [13, None, 24]]

print("The list is:")
print(my_list)

my_list.sort(key=get_None_freq)

print("The result is:")
print(my_list)

Output

The list is:
[[None, 24], [None, 33, 3, None], [42, 24, 55], [13, None, 24]]
The result is:
[[42, 24, 55], [None, 24], [13, None, 24], [None, 33, 3, None]]

How It Works

The get_None_freq function counts None values in each row:

  • Uses list comprehension to iterate through elements in a row

  • The not element condition evaluates to True for None values (since not None is True)

  • Returns the length of filtered elements, which represents the count of None values

  • The sort()

Alternative Using Lambda

You can achieve the same result using a lambda function ?

my_list = [[None, 24], [None, 33, 3, None], [42, 24, 55], [13, None, 24]]

print("Original list:")
print(my_list)

my_list.sort(key=lambda row: len([x for x in row if x is None]))

print("Sorted by None frequency:")
print(my_list)
Original list:
[[None, 24], [None, 33, 3, None], [42, 24, 55], [13, None, 24]]
Sorted by None frequency:
[[42, 24, 55], [None, 24], [13, None, 24], [None, 33, 3, None]]

Conclusion

Sorting a matrix by None frequency involves counting None values in each row and using that count as a sorting key. The sort() method with a custom key function arranges rows from lowest to highest None count.

Updated on: 2026-03-26T01:26:18+05:30

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements