Count occurrence of all elements of list in a tuple in Python


We have a list and tuple. We match the elements of the list with the elements of the tuple and account the number of elements in the table matching with the elements of the list.

With Counter

We use the counter function from collections to get the count of every element in the tuple. Again design a for and in condition find those elements which are present in the the list and part of the counting result from the tuple.

Example

 Live Demo

from collections import Counter
Atup = ('Mon', 'Wed', 'Mon', 'Tue', 'Thu')
Alist = ['Mon', 'Thu']
# Given Tuple and list
print("Given tuple :\n",Atup)
print("Given list :\n",Alist)
cnt = Counter(Atup)
res= sum(cnt[i] for i in Alist)
print("Number of list elements in the tuple: \n",res)

Output

Running the above code gives us the following result −

Given tuple :
('Mon', 'Wed', 'Mon', 'Tue', 'Thu')
Given list :
['Mon', 'Thu']
Number of list elements in the tuple:
3

With sum()

In this approach we apply the sum function. If the value from the tuple is present in the list we return 1 else return 0. Show the sum function will give the result of only those elements from the list which are present in tuple.

Example

Atup = ('Mon', 'Wed', 'Mon', 'Tue', 'Thu')
Alist = ['Mon', 'Thu','Mon']
Alist = set(Alist)
# Given Tuple and list
print("Given tuple :\n",Atup)
print("Given list :\n",Alist)
res= sum(1 for x in Atup if x in Alist)
print("Number of list elements in the tuple: \n",res)

Output

Running the above code gives us the following result −

Given tuple :
('Mon', 'Wed', 'Mon', 'Tue', 'Thu')
Given list :
{'Mon', 'Thu'}
Number of list elements in the tuple:
3

Updated on: 04-Jun-2020

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements