Open In App

Frequency of Elements from Other List – Python

Last Updated : 08 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list of elements and another list containing specific values and our task is to count the occurrences of these specific values in the first list “a” and return their frequencies. For example: a = [1, 2, 2, 3, 4, 2, 5, 3, 1], b = [1, 2, 3]. Here b contains the elements whose frequency we need to find in a hence the output should be: {1: 2, 2: 3, 3: 2}

Using collections.Counter

Counter class from the collections module makes it easy to count occurrences in a list and we can use it to get the frequency of all elements in a and then filter only the elements from b.

Python
from collections import Counter  

a = [1, 2, 2, 3, 4, 2, 5, 3, 1]  
b = [1, 2, 3]  

freq = Counter(a)  
res = {x: freq[x] for x in b}  

print(res)  

Output
{1: 2, 2: 3, 3: 2}

Explanation:

  • Counter(a) creates a dictionary-like object where keys are elements of a and values are their counts.
  • {x: freq[x] for x in b} filters only the required elements.

Using Dictionary Comprehension

We can use a dictionary comprehension with the count() method to count the occurrences of each element in b directly from a.

Python
a = [1, 2, 2, 3, 4, 2, 5, 3, 1]  
b = [1, 2, 3]  

res = {x: a.count(x) for x in b}  

print(res)  

Output
{1: 2, 2: 3, 3: 2}

Explanation: {x: a.count(x) for x in b} iterates over b and calculates the count of each x in a and count(x) method returns how many times x appears in a.

Using map() with count()

map() function can be used to apply count() on each element of b creating the frequency dictionary efficiently.

Python
a = [1, 2, 2, 3, 4, 2, 5, 3, 1]  
b = [1, 2, 3]  

res = dict(zip(b, map(a.count, b)))  

print(res)  

Output
{1: 2, 2: 3, 3: 2}

Explanation:

  • map(a.count, b) applies a.count(x) to each x in b and zip(b, map(a.count, b)) pairs each element of b with its count.
  • dict(zip(…)) converts the result into a dictionary.

Using for Loop

A simple for loop can be used to count occurrences of elements from b in a.

Python
a = [1, 2, 2, 3, 4, 2, 5, 3, 1]  
b = [1, 2, 3]  

res = {}  
for x in b:  
    res[x] = a.count(x)  

print(res)  

Output
{1: 2, 2: 3, 3: 2}

Explanation:

  • We initialize an empty dictionary result and loop through each element x in b.
  • a.count(x) is used to count occurrences of x in a and the result is stored in result[x].


Next Article

Similar Reads