- Related Questions & Answers
- List frequency of elements in Python
- Find sum of elements in list in Python program
- Python program to find sum of elements in list
- Find frequency of given character at every position in list of lists in Python
- How to find the sum of two list elements in R?
- Program to find largest sum of non-adjacent elements of a list in Python
- Find sum of all elements in a matrix except the elements in row and-or column of given cell in Python
- Python - Ways to format elements of given list
- Finding frequency in list of tuples in Python
- Count Frequency of Highest Frequent Elements in Python
- Program to find sum of non-adjacent elements in a circular list in python
- Find common elements in list of lists in Python
- C/C++ Program to find the sum of elements in a given array
- Program to find the sum of all digits of given number in Python
- Program to find maximum sum of popped k elements from a list of stacks in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

A given list has many repeated items. We are interested in finding out the sum of the frequency of some such items which are repeated in the list. Below are the approaches how we can achieve this.

We have two lists. One has the list of values and other has the values whose frequency needs to be checked from the first list. So we create a for loop to count the number of occurrences of the elements from the second list in the first list and then apply the sum function to get the final sum of frequency.

chk_list= ['Mon', 'Tue'] big_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue'] # Apply sum res = sum(big_list.count(elem) for elem in chk_list) # Printing output print("Given list to be analysed: \n", big_list) print("Given list to with values to be analysed:\n", chk_list) print("Sum of the frequency: ", res)

Running the above code gives us the following result −

Given list to be analysed: ['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue'] Given list to with values to be analysed: ['Mon', 'Tue'] Sum of the frequency: 5

The Counter function from collections module can get the desired result by applying it to the list whose values have to be analysed while looping through the smaller list which has only the elements whose frequency needs to be established.

from collections import Counter chk_list= ['Mon', 'Tue'] big_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue'] # Apply Counter res = sum(Counter(big_list)[x] for x in chk_list) # Printing output print("Given list to be analysed: \n", big_list) print("Given list to with values to be analysed:\n", chk_list) print("Sum of the frequency: ", res)

Running the above code gives us the following result −

Given list to be analysed: ['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue'] Given list to with values to be analysed: ['Mon', 'Tue'] Sum of the frequency: 5

Advertisements