
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Count tuples occurrence in list of tuples in Python
- Find all elements count in list in Python
- Python - Join tuple elements in a list
- Count frequencies of all elements in array in Python
- Flatten tuple of List to tuple in Python
- Modulo of tuple elements in Python
- Python – Nearest occurrence between two elements in a List
- Sort tuple based on occurrence of first element in Python
- Last occurrence of some element in a list in Python
- Python program to count the elements in a list until an element is a Tuple?
- List consisting of all the alternate elements in Python
- Count the elements till first tuple in Python
- Python - First occurrence of one list in another
- Grouped summation of tuple list in Python
- Python – Concatenate Rear elements in Tuple List
Advertisements