
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Finding frequency in list of tuples in Python
Many different types of data container can get mixed up in python. A list can have elements each of which is a tuple. In this article we will take such a list and find the frequency of element in the tuples which are themselves elements of a list.
Using count and map
We apply a lambda function to count through each of the first element in the tuples present in the list. Then apply a map function to arrive at the total count of the element we are searching for.
Example
# initializing list of tuples listA = [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')] # Given list print("Given list of tuples : " ,listA) # Frequency in list of tuples Freq_res = list(map(lambda i: i[0], listA)).count('Apple') # printing result print("The frequency of element is : ",Freq_res)
Output
Running the above code gives us the following result:
Given list of tuples : [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')] The frequency of element is : 2
With Counter
We can also implement Counter which will count the number of occurrences of an element. We use a for loop to go through each of the tuple present in the list.
Example
from collections import Counter # initializing list of tuples listA = [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')] # Given list print("Given list of tuples : " ,listA) # Frequency in list of tuples Freq_res = Counter(i[0] for i in listA)['Apple'] # printing result print("The frequency of element is : ",Freq_res)
Output
Running the above code gives us the following result −
Given list of tuples : [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')] The frequency of element is : 2
- Related Articles
- Combining tuples in list of tuples in Python
- Count tuples occurrence in list of tuples in Python
- Remove duplicate tuples from list of tuples in Python
- Convert list of tuples into list in Python
- Summation of tuples in list in Python
- Convert list of tuples to list of list in Python
- Custom sorting in list of tuples in Python
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- Update a list of tuples using another list in Python
- Remove tuples from list of tuples if greater than n in Python
- Python program to find Tuples with positive elements in List of tuples
- Convert dictionary to list of tuples in Python
- List of tuples to dictionary conversion in Python
- Convert list of tuples into digits in Python

Advertisements