Python – Test if Rows have Similar frequency

When checking if rows have similar frequency in a list of lists, you can use Python's Counter class along with the all() function to compare element frequencies across all rows.

Example

Here's how to test if all rows contain the same elements with identical frequencies ?

from collections import Counter

my_list = [[21, 92, 64, 11, 3], [21, 3, 11, 92, 64], [64, 92, 21, 3, 11]]

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

my_result = all(dict(Counter(row)) == dict(Counter(my_list[0])) for row in my_list)

if my_result == True:
    print("All rows have similar frequency")
else:
    print("All rows do not have similar frequency")
The list is :
[[21, 92, 64, 11, 3], [21, 3, 11, 92, 64], [64, 92, 21, 3, 11]]
All rows have similar frequency

How It Works

The solution works by following these steps:

  • Counter(row) creates a frequency count for each row
  • dict(Counter(row)) converts the Counter object to a dictionary
  • Each row's frequency dictionary is compared with the first row's frequency dictionary
  • all() returns True only if all comparisons are True

Testing with Different Frequencies

Let's test with rows that have different element frequencies ?

from collections import Counter

different_freq_list = [[1, 2, 3, 1], [1, 2, 3, 2], [1, 2, 3, 3]]

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

result = all(dict(Counter(row)) == dict(Counter(different_freq_list[0])) for row in different_freq_list)

if result:
    print("All rows have similar frequency")
else:
    print("All rows do not have similar frequency")
The list is :
[[1, 2, 3, 1], [1, 2, 3, 2], [1, 2, 3, 3]]
All rows do not have similar frequency

Alternative Approach Using Counter Directly

You can also compare Counter objects directly without converting to dictionaries ?

from collections import Counter

data = [[5, 10, 5, 20], [10, 5, 20, 5], [20, 5, 10, 5]]

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

first_counter = Counter(data[0])
result = all(Counter(row) == first_counter for row in data)

print(f"All rows have similar frequency: {result}")
The list is :
[[5, 10, 5, 20], [10, 5, 20, 5], [20, 5, 10, 5]]
All rows have similar frequency: True

Conclusion

Use Counter with all() to efficiently check if all rows have identical element frequencies. This approach works regardless of element order within rows.

Updated on: 2026-03-26T00:52:13+05:30

213 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements