
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements