# Python – Count frequency of sublist in given list

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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, 90]
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 resultant list is : ")
print(my_result)

## Output

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, 90]
The resultant list is :
1

## Explanation

• A list of integers is defined and is displayed on the console.

• The sub-list is defined and is displayed on the console.

• A list comprehension is used to iterate over the list, and use an ‘if’ condition.

• This condition checks if the sum of the length of the sub-list and the specific index and the sublist are equal.

• If yes, they are appended to a list, and assigned to a variable.

• This is displayed as output on the console.

Updated on 13-Sep-2021 11:01:44