Python - Assign Frequency to Tuples
Last Updated :
02 May, 2023
Given tuple list, assign frequency to each tuple in list.
Input : test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (9, ), (2, 7)]
Output : [(6, 5, 8, 2), (2, 7, 2), (9, 1)]
Explanation : (2, 7) occurs 2 times, hence 2 is append in tuple.
Input : test_list = [(2, 7), (2, 7), (6, 5, 8), (9, ), (2, 7)]
Output : [(6, 5, 8, 1), (2, 7, 3), (9, 1)]
Explanation : (2, 7) occurs 3 times, hence 3 is append in tuple.
Method #1 : Using Counter() + items() + * operator + list comprehension
In this, we extract the frequency using Counter(), fetch frequency numbers using items(), * operator is used to unpack elements and list comprehension is used to assign this to all elements in tuple list.
Python3
# Python3 code to demonstrate working of
# Assign Frequency to Tuples
# Using Counter() + items() + * operator + list comprehension
from collections import Counter
# initializing list
test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
# printing original list
print("The original list is : " + str(test_list))
# one-liner to solve problem
# assign Frequency as last element of tuple
res = [(*key, val) for key, val in Counter(test_list).items()]
# printing results
print("Frequency Tuple list : " + str(res))
OutputThe original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Method #2 : Using most_common() + Counter() + * operator + list comprehension
This is similar to the above method, just most_common() performs sort operation on list, which is not necessary.
Python3
# Python3 code to demonstrate working of
# Assign Frequency to Tuples
# Using most_common() + Counter() + * operator + list comprehension
from collections import Counter
# initializing list
test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
# printing original list
print("The original list is : " + str(test_list))
# most_common performs sort on arg. list
# assign Frequency as last element of tuple
res = [(*key, val) for key, val in Counter(test_list).most_common()]
# printing results
print("Frequency Tuple list : " + str(res))
OutputThe original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Method #3 : Using count(),list(),tuple() methods
Python3
# Python3 code to demonstrate working of
# Assign Frequency to Tuples
# initializing list
test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
# printing original list
print("The original list is : " + str(test_list))
# one-liner to solve problem
# assign Frequency as last element of tuple
res=[]
for i in test_list:
if i not in res:
res.append(i)
res1=[]
for i in res:
x=list(i)
x.append(test_list.count(i))
p=tuple(x)
res1.append(p)
# printing results
print("Frequency Tuple list : " + str(res1))
OutputThe original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9,), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Method #4 : Using operator.countOf(),list(),tuple() methods
Python3
# Python3 code to demonstrate working of
# Assign Frequency to Tuples
import operator as op
# initializing list
test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
# printing original list
print("The original list is : " + str(test_list))
# one-liner to solve problem
# assign Frequency as last element of tuple
res=[]
for i in test_list:
if i not in res:
res.append(i)
res1=[]
for i in res:
x=list(i)
x.append(op.countOf(test_list,i))
p=tuple(x)
res1.append(p)
# printing results
print("Frequency Tuple list : " + str(res1))
OutputThe original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9,), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Time Complexity: O(N*N), where n is the length of the given tuple
Auxiliary Space: O(N*N)
METHOD 5:Using dictionary and list comprehension: The method returns the value for a key if it exists in the dictionary, otherwise it returns a default value of 0. This allows us to simplify the if-else statement in the for a loop. The rest of the solution is the same as before, creating a list of tuples using list comprehension.
- Create an empty dictionary to store the frequencies of each tuple.
- Iterate over each tuple in the given list and add it to the dictionary if it doesn't exist, with a frequency of 1. If the tuple already exists, increment its frequency by 1.
- Use a list comprehension to create a new list of tuples with the original tuples and their frequencies.
Python3
# Python program for the above approach
# Function to assign frequency
def assign_frequency(lst):
freq_dict = {}
for tup in lst:
if tup in freq_dict:
freq_dict[tup] += 1
else:
freq_dict[tup] = 1
return [(key + (value,)) for key, value in freq_dict.items()]
# Driver Code
lst = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
print(assign_frequency(lst))
Output[(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Time Complexity: O(n) where n is the number of tuples in the list.
Space Complexity: O(n) since the dictionary stores the frequencies of each tuple.
METHOD 6:Using reduce():
Algorithm:
- Import Counter and reduce from their respective modules.
- Initialize the original list test_list.
- Print the original list.
- Use reduce to merge all the tuples in the list into a single Counter object that counts the frequency of each tuple.
- Create a list of tuples by iterating over the Counter object, unpacking each tuple into the tuple elements and frequency.
- Sort the list of tuples in descending order of frequency.
- Print the final list.
Python3
from collections import Counter
from functools import reduce
# initializing list
test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
# printing original list
print("The original list is : " + str(test_list))
# using reduce to merge tuples and sum their counts
res = reduce(lambda x, y: x + y, [Counter([t]) for t in test_list])
# creating list of tuples with frequency as last element
res = [(*key, val) for key, val in res.items()]
# sorting the list in descending order of frequency
res.sort(key=lambda x: x[-1], reverse=True)
# printing results
print("Frequency Tuple list : " + str(res))
#This code is contributed by Rayudu.
OutputThe original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9,), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Time complexity: O(n log n), where n is the length of the original list. This is because sorting the list of tuples takes O(n log n) time.
Space complexity: O(n), where n is the length of the original list. This is because we create a new list of tuples with the same length as the original list. The Counter object also takes O(n) space.
METHOD 7:Using groupby():
Algorithm:
- Create an empty dictionary, freq_dict.
- For each element in the list, do the following:
a. Check if the element is already in the dictionary.
b. If it is not in the dictionary, add it with a value of 1.
c. If it is in the dictionary, increment its value by 1. - Create an empty list, freq_list.
- For each key-value pair in the dictionary, create a tuple (key, value) and append it to the freq_list.
- Sort the freq_list in ascending order based on the second element (frequency).
- Return the freq_list.
Python3
import itertools
# initializing list
test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
# printing original list
print("The original list is : " + str(test_list))
# use groupby to get unique rows and their counts
res = []
for row, group in itertools.groupby(sorted(test_list)):
count = sum(1 for _ in group)
res.append(row + (count,))
# print result
print("Frequency Tuple list : " + str(res))
#This code is contributed by Vinay pinjala.
OutputThe original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9,), (2, 7)]
Frequency Tuple list : [(2, 7, 2), (6, 5, 8, 3), (9, 1)]
Time complexity:
The time complexity of this algorithm is O(n log n), where n is the length of the input list. This is because the algorithm involves iterating through the input list once (O(n)), adding and updating dictionary elements (which has an average case time complexity of O(1)), creating a new list of tuples (O(n)), and sorting that list using Python's built-in sorted function (which has a time complexity of O(n log n)).
Auxiliary Space:
The space complexity of this algorithm is O(n), where n is the length of the input list. This is because the algorithm creates a dictionary with up to n unique elements, a list with n elements, and several temporary variables (which have a constant space complexity).
Similar Reads
Python - False values Frequency
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals that match the particular condition to have a distinguish which to not match for further utilization like in data Science. Lets discuss certain ways
5 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 | Chunk Tuples to N
Sometimes, while working with data, we can have a problem in which we may need to perform chunking of tuples each of size N. This is popular in applications in which we need to supply data in chunks. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension
4 min read
Python | Tuple Column element frequency
In Python, we need to handle various forms of data and one among them is a 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 Kth element in the list of tuples. Letâs discuss certain ways in which this can
5 min read
Python | Finding frequency in list of tuples
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 cert
6 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
Creating Sets of Tuples in Python
Tuples are an essential data structure in Python, providing a way to store ordered and immutable sequences of elements. When combined with sets, which are unordered collections of unique elements, you can create powerful and efficient data structures for various applications. In this article, we wil
3 min read
Python | Adding N to Kth tuple element
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let's discuss certain ways in which N can be added to Kth element of tuple in list. Method #1 : Using loop Using loops this task c
3 min read
Python - Keys Values equal frequency
Given a dictionary, count instances where keys are equal to values. Input : test_dict = {5:5, 8:9, 7:8, 1:2, 10:10, 4:8} Output : 2 Explanation : At 2 instances, keys are equal to values.Input : test_dict = {5:4, 8:9, 7:8, 1:2, 10:10, 4:8} Output : 1 Explanation : At 1 instance, key is equal to valu
4 min read
Python | Addition of tuples
Sometimes, while working with records, we might have a common problem of adding contents of one tuple with the corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records. Let's discuss certain ways in which this task can be performed. Metho
5 min read