Given a tuple and a list as input, write a Python program to count the occurrences of all items of the list in the tuple.
Input : tuple = ('a', 'a', 'c', 'b', 'd') list = ['a', 'b'] Output : 3 Input : tuple = (1, 2, 3, 1, 4, 6, 7, 1, 4) list = [1, 4, 7] Output : 6
Approach #1 : Naive Approach
The first approach is the naive approach. Use a for loop and traverse through the given list and count the occurrence of each item of tuple in a list. Finally, return the count.
Approach #2 : Using Counter
From Python Collections module, import counter to solve the given problem. A Counter is a container that keeps track of how many times equivalent values are added. Having saved the resultant in ‘counts’, we use a for loop and count how many times each item in list occurs in ‘counts’ and sum it to give the final output.
Approach #3 : Using Set
Another method of solving the given problem is using set data structure. Simply convert the given list into a set, which removes all duplicates. And now, for each item of list, count its occurrence in tuple and sum them.
Approach #4 : Using Python dictionary
Get each item of tuple and its frequency as key:value pair in Python dictionary, then using a for loop, for each item of list, count its occurrence in tuple and sum them.
Approach #5 : Python
Python numpy gives us a direct method to find the solution for the given problem, and that is
numpy.in1d(). This method test whether each element of a 1-D array is also present in a second array. Since list is also a 1-D array, this method can be applied here.
- Python | Count the elements in a list until an element is a Tuple
- Python | Join tuple elements in a list
- Python | Sort tuple based on occurrence of first element
- Python | Count tuples occurrence in list of tuples
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Pair and combine nested list to tuple list
- Python | Find all elements count in list
- Python | Convert a list into a tuple
- Python | Last occurrence of some element in a list
- Python | Reverse each tuple in a list of tuples
- Python | Modifying tuple contents with list
- Python | Grouped summation of tuple list
- Python | Convert a list into tuple of lists
- Python | Dictionary to list of tuple conversion
- Python | Summation of list as tuple attribute
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.