# Python – Cumulative Row Frequencies in List

• Last Updated : 28 Feb, 2023

Given Matrix, the task is to write a Python program to get total counts of occurrences from the row.

Input : test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]], ele_list = [1, 2, 7]
Output : [2, 2, 2, 5]
Explanation : 2 occurs 2 times in row 1 and so on.

Input : test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4]], ele_list = [1, 2, 7]
Output : [2, 2]
Explanation : 2 occurs 2 times in row 1 and so on.

Method #1 : Using Counter() + list comprehension

In this, we perform the task of getting all the frequencies of all rows, and then check in the list occurrence of the required element from the row, sum() is used to get a summation of extracted frequencies in rows.

## Python3

 # Python3 code to demonstrate working of# Cumulative Row Frequencies# Using Counter() + list comprehensionfrom collections import Counter # initializing listtest_list = [[10, 2, 3, 2, 3],             [5, 5, 4, 7, 7, 4],             [1, 2], [1, 1, 2, 2, 2]] # printing original listprint("The original list is : " + str(test_list)) # initializing ele_listele_list = [1, 2, 7] # getting each rows counterfreqs = [Counter(ele) for ele in test_list] # getting summation of present valuesres = [sum([freq[wrd] for wrd in ele_list if wrd in freq]) for freq in freqs] # printing resultprint("Cumulative Frequencies : " + str(res))

Output:

The original list is : [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]]
Cumulative Frequencies : [2, 2, 2, 5]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using sum() + list comprehension

In this, we perform the task of getting summation using sum(), and list comprehension is used to check for elements in the check list and iterate through rows.

## Python3

 # Python3 code to demonstrate working of# Cumulative Row Frequencies# Using sum() + list comprehension # initializing listtest_list = [[10, 2, 3, 2, 3],             [5, 5, 4, 7, 7, 4],             [1, 2], [1, 1, 2, 2, 2]] # printing original listprint("The original list is : " + str(test_list)) # initializing ele_listele_list = [1, 2, 7] # getting summationres = [sum(ele in ele_list for ele in sub) for sub in test_list] # printing resultprint("Cumulative Frequencies : " + str(res))

Output:

The original list is : [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]]
Cumulative Frequencies : [2, 2, 2, 5]

Time Complexity: O(n)
Auxiliary Space: O(n)

My Personal Notes arrow_drop_up