Python | Finding frequency in list of tuples
Last Updated :
15 May, 2023
In python we need to handle various forms of data and one among them is list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the 1st element in list of tuple which can be extended to any index. Let's discuss certain ways in which this can be performed.
Method #1 : Using map() + count() The map function can be used to accumulate the indices of all the tuples in a list and the task of counting the frequency can be done using the generic count function of python library.
Python3
# Python3 code to demonstrate
# finding frequency in list of tuples
# using map() + count()
# initializing list of tuples
test_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
# printing the original list
print ("The original list is : " + str(test_list))
# using map() + count()
# finding frequency in list of tuples
res = list(map(lambda i : i[0], test_list)).count('Geeks')
# printing result
print ("The frequency of element is : " + str(res))
OutputThe original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using Counter() + list comprehension List comprehension performs the task of getting the first element of the tuples and the counting part is handled by Counter function of collection library.
Python3
# Python3 code to demonstrate
# finding frequency in list of tuples
# using Counter() + list comprehension
from collections import Counter
# initializing list of tuples
test_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
# printing the original list
print ("The original list is : " + str(test_list))
# using Counter() + list comprehension
# finding frequency in list of tuples
res = Counter(i[0] for i in test_list)
# printing result
print ("The frequency of element is : " + str(res['Geeks']))
OutputThe original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2
Method #3 : Dictionary comprehension and the get() method
To use dictionary comprehension and the get() method to find the frequency of the element 'Geeks' in the list of tuples test_list, you can do the following:
Python3
# initializing list of tuples
test_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
# create a dictionary to store the frequency of each element looping and the get() method
frequency = {}
for element in test_list:
frequency[element[0]] = frequency.get(element[0], 0) + 1
# print the frequency of the element 'Geeks'
print(frequency['Geeks'])
#This code is contributed by Edula Vinay Kumar Reddy
If the element is already in the dictionary, the get() method returns its current value, and this value is incremented by 1. This allows us to count the frequency of each element in the list of tuples.
Time complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using map() + operator.countOf() method
The map function can be used to accumulate the indices of all the tuples in a list and the task of counting the frequency can be done using the operator.countOf function of python library.
Python3
# Python3 code to demonstrate
# finding frequency in list of tuples
# using map() + operator.countOf()
import operator as op
# initializing list of tuples
test_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
# printing the original list
print ("The original list is : " + str(test_list))
# using map() + operator.countOf()
# finding frequency in list of tuples
res = op.countOf(list(map(lambda i : i[0], test_list)),'Geeks')
# printing result
print ("The frequency of element is : " + str(res))
OutputThe original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2
Time complexity: O(n*n)
Auxiliary Space: O(1)
Method #5: Using np.unique
The np.unique function in NumPy can be used to find the unique elements in a given array and their frequencies.
Algorithm:
- Initialize a NumPy array with the first elements of each tuple in the list of tuples.
- Use np.unique with the return_counts parameter set to True to get the unique elements and their frequencies.
- Find the index of the element to get its frequency.
Python3
# Python3 code to demonstrate
# finding frequency in list of tuples
# using np.unique
import numpy as np
# initializing list of tuples
test_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
# printing the original list
print("The original list is : " + str(test_list))
# initializing NumPy array with first elements of tuples
arr = np.array([t[0] for t in test_list])
# using np.unique to get unique elements and their frequencies
unique, counts = np.unique(arr, return_counts=True)
# finding the index of the element
index = np.where(unique == 'Geeks')[0][0]
# printing result
print("The frequency of element is : " + str(counts[index]))
Output:
The original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2
Time Complexity: O(n log n), where n is the length of the list test_list (due to the sorting operation performed by np.unique).
Auxiliary Space: O(n), where n is the number of elements in the NumPy array arr.
METHOD 6:Using re-module.
APPROACH:
This program uses regular expressions in Python to find the frequency of a given element in a list of tuples. The program first creates a regular expression pattern that matches strings that start with the desired element followed by a word boundary. It then uses a generator expression to iterate over the list of tuples and count the number of tuples whose first element matches the pattern. Finally, it prints the result.
ALGORITHM:
1. Initialize the list of tuples and the element to be searched for.
2. Create a regular expression pattern that matches strings starting with the desired element followed by a word boundary.
3. Use a generator expression to iterate over the list of tuples and count the number of tuples whose first element matches the pattern.
4. Print the result.
Python3
import re
lst = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
element = 'Geeks'
pattern = re.compile(rf"^{element}\b")
count = sum(1 for tpl in lst if pattern.match(tpl[0]))
print("The frequency of", element, "is", count)
OutputThe frequency of Geeks is 2
Time complexity:
The time complexity of this program is O(n), where n is the number of tuples in the list. This is because the program needs to iterate over each tuple in the list once to count the frequency of the desired element.
Space complexity:
The space complexity of this program is O(1), as the program only uses a constant amount of additional memory to store the regular expression pattern, the count variable, and the element to be searched for. The memory used by the list of tuples is not counted, as it is part of the input.
Similar Reads
Python - Find frequency of given Datatype in tuple
Sometimes, while working with Python records, we can have a problem in which we need to extract count of any data type occurred in tuple. This can have application in various domains such as day-day programming and web development. Let's discuss certain ways in which this task can be performed. Inpu
6 min read
Python - Step Frequency of elements in List
Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
4 min read
Python - Values Frequency Index List
Sometimes, while working with Python tuples, we can have a problem in which we need to extract the frequency of each value in tuple. This has been solved earlier. We can have a modification in which we need to create list in which index represents the key and value of it represents the frequency of
4 min read
Python - Count frequency of Sublist in given list
Given a List and a sublist, count occurrence of sublist in list. Input : test_list = [4, 5, 3, 5, 7, 8, 3, 5, 7, 2, 3, 5, 7], sublist = [3, 5, 7] Output : 3 Explanation : 3, 5, 7 occurs 3 times. Input : test_list = [4, 5, 3, 5, 8, 8, 3, 2, 7, 2, 3, 6, 7], sublist = [3, 5, 7] Output : 0 Explanation :
3 min read
Python - Maximum frequency in Tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to find the maximum frequency element in the tuple. Tuple, being quite a popular container, this type of problem is common across the web development domain. Let's discuss certain ways in which this task can be perfo
5 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways
7 min read
Python - Elements frequency in Tuple
Given a Tuple, find the frequency of each element. Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on.. Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. Method #1 Using def
7 min read
Python - Sort by Frequency of second element in Tuple List
Given list of tuples, sort by frequency of second element of tuple. Input : test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Output : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)] Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first. Input : test_l
6 min read
Python | Find top K frequent elements from a list of tuples
Given a list of tuples with word as first element and its frequency as second element, the task is to find top k frequent element. Below are some ways to above achieve the above task. Method #1: Using defaultdict Python3 # Python code to find top 'k' frequent element # Importing import collections f
5 min read
Python - Elements frequency in Tuple Matrix
Sometimes, while working with Python Tuple Matrix, we can have a problem in which we need to get the frequency of each element in it. This kind of problem can occur in domains such as day-day programming and web development domains. Let's discuss certain ways in which this problem can be solved. Inp
5 min read