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
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 : 2Advertisements