Python – Count frequency of sublist in given list

When it is required to count the frequency of a sub−list in a given list, a list comprehension and the 'len' method along with the 'if' condition are used.

Example

Below is a demonstration of the same −

my_list = [23, 33, 45, 67, 54, 43, 33, 45, 67, 83, 33, 45, 67, 90, 0]

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

sub_list = [33, 45, 67]
print("The sub-list is:")
print(sub_list)

my_result = len([sub_list for index in range(len(my_list)) if my_list[index : index + len(sub_list)] == sub_list])

print("The frequency count is:")
print(my_result)
The list is:
[23, 33, 45, 67, 54, 43, 33, 45, 67, 83, 33, 45, 67, 90, 0]
The sub-list is:
[33, 45, 67]
The frequency count is:
3

Using a Function Approach

Here's a more readable approach using a function −

def count_sublist_frequency(main_list, target_sublist):
    count = 0
    sublist_len = len(target_sublist)
    
    for i in range(len(main_list) - sublist_len + 1):
        if main_list[i:i + sublist_len] == target_sublist:
            count += 1
    
    return count

# Example usage
numbers = [1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 5]
pattern = [1, 2, 3]

frequency = count_sublist_frequency(numbers, pattern)
print(f"Pattern {pattern} appears {frequency} times")
Pattern [1, 2, 3] appears 3 times

How It Works

  • The algorithm iterates through the main list using a sliding window approach.

  • For each position, it extracts a slice of the same length as the target sublist.

  • It compares this slice with the target sublist for equality.

  • If they match, the counter is incremented.

  • The final count represents how many times the sublist appears consecutively.

Edge Cases

Here are some edge cases to consider −

# Empty sublist
main_list = [1, 2, 3, 4]
empty_sublist = []
result = len([empty_sublist for i in range(len(main_list)) if main_list[i:i + len(empty_sublist)] == empty_sublist])
print(f"Empty sublist frequency: {result}")

# Sublist longer than main list
short_list = [1, 2]
long_sublist = [1, 2, 3, 4, 5]
result2 = len([long_sublist for i in range(len(short_list)) if short_list[i:i + len(long_sublist)] == long_sublist])
print(f"Longer sublist frequency: {result2}")

# Overlapping patterns
overlap_list = [1, 1, 1, 1]
pattern = [1, 1]
result3 = len([pattern for i in range(len(overlap_list)) if overlap_list[i:i + len(pattern)] == pattern])
print(f"Overlapping pattern frequency: {result3}")
Empty sublist frequency: 5
Longer sublist frequency: 0
Overlapping pattern frequency: 3

Conclusion

Use list comprehension with slicing to count sublist frequencies efficiently. The sliding window approach checks each possible position for consecutive matches, making it suitable for finding overlapping patterns in lists.

Updated on: 2026-03-26T01:41:09+05:30

524 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements