Open In App

Python – Assign Frequency to Tuples

Last Updated : 02 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

The 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))


Output

The 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))


Output

The 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))


Output

The 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:

  1. Import Counter and reduce from their respective modules.
  2. Initialize the original list test_list.
  3. Print the original list.
  4. Use reduce to merge all the tuples in the list into a single Counter object that counts the frequency of each tuple.
  5. Create a list of tuples by iterating over the Counter object, unpacking each tuple into the tuple elements and frequency.
  6. Sort the list of tuples in descending order of frequency.
  7. 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.


Output

The 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:

  1. Create an empty dictionary, freq_dict.
  2. 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.
  3. Create an empty list, freq_list.
  4. For each key-value pair in the dictionary, create a tuple (key, value) and append it to the freq_list.
  5. Sort the freq_list in ascending order based on the second element (frequency).
  6. 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.


Output

The 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 | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to count unique #
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 in which this can be performed. Method #1: Using
7 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
Python | How to Concatenate tuples to nested tuples
Sometimes, while working with tuples, we can have a problem in which we need to convert individual records into a nested collection yet remaining as separate element. Usual addition of tuples, generally adds the contents and hence flattens the resultant container, this is usually undesired. Let's discuss certain ways in which this problem is solved
6 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [
8 min read
Python program to find Tuples with positive elements in List of tuples
Given a list of tuples. The task is to get all the tuples that have all positive elements. Examples: Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements. Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple wit
10 min read
Practice Tags :