Open In App

Python – Elements frequency in Tuple

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

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

In this, we perform task of getting all elements and assigning frequency using defaultdict which maps each element with key and then frequency can be incremented.

Python3




# Python3 code to demonstrate working of
# Elements frequency in Tuple
# Using defaultdict()
from collections import defaultdict
 
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
res = defaultdict(int)
for ele in test_tup:
     
    # incrementing frequency
    res[ele] += 1
 
# printing result
print("Tuple elements frequency is : " + str(dict(res)))


Output

The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}

Time complexity: O(n), where n is the length of the tuple test_tup. This is because the program iterates through the tuple once to increment the frequency of each element using a dictionary. The += operation and dictionary lookup both take constant time.
Auxiliary space: O(n), where n is the length of the tuple test_tup. This is because the program uses a dictionary to store the frequency of each element in the tuple, which can potentially have n unique elements.

Method #2 : Using Counter()

This is straight forward way to solve this problem. In this, we just employ this function and it returns frequency of elements in container, in this case tuple.

Python3




# Python3 code to demonstrate working of
# Elements frequency in Tuple
# Using Counter()
from collections import Counter
 
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# converting result back from defaultdict to dict
res = dict(Counter(test_tup))
 
# printing result
print("Tuple elements frequency is : " + str(res))


Output

The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}

Time complexity: O(n), where n is the number of elements in the tuple.
Auxiliary space: O(n), as the Counter() method creates a dictionary that stores the frequency of each element in the tuple.

Method #3 : Using count() method.

Python3




# Python3 code to demonstrate working of
# Elements frequency in Tuple
 
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
res = dict()
x=list(test_tup)
y=[]
for i in x:
    if i not in y:
        y.append(i)
for i in y:
    res[i]=x.count(i)
# printing result
print("Tuple elements frequency is : " + str(res))


Output

The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}

The time complexity of this program is O(n^2) because of the nested loops used to count the frequency of each element. 

The auxiliary space complexity of this program is O(n) because the program uses two lists x and y to store the tuple elements and unique elements, respectively, and a dictionary res to store the frequency count of each element. 

Method #4 : Using operator.countOf() method.

Python3




# Python3 code to demonstrate working of
# Elements frequency in Tuple
import operator as op
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
res = dict()
x=list(test_tup)
y=[]
for i in x:
    if i not in y:
        y.append(i)
for i in y:
    res[i]=op.countOf(x,i)
# printing result
print("Tuple elements frequency is : " + str(res))


Output

The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}

Time Complexity: O(N), where n is the length of the given tuple
Auxiliary Space: O(n)

Method 5:dictionary and loop over the elements in the tuple to count their frequency. 

This code is designed to count the frequency of each element in the tuple test_tup. It does this by creating an empty dictionary freq_dict to store the counts, and then looping over each element of the tuple. For each element, it checks if that element is already a key in the dictionary freq_dict. If it is, it increments the value associated with that key (which represents the count of that element in the tuple). If it isn’t, it adds a new key to the dictionary with a value of 1. Once the loop has finished, the code prints out the resulting dictionary, which contains the counts for each unique element in the tuple.

Python3




test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
 
freq_dict = {}
for elem in test_tup:
    if elem in freq_dict:
        freq_dict[elem] += 1
    else:
        freq_dict[elem] = 1
 
print("Tuple elements frequency is : " + str(freq_dict))


Output

Tuple elements frequency is : {4: 3, 5: 4, 6: 2}

Time complexity: O(n), where n is the length of the tuple. 
Auxiliary space: O(k), where k is the number of unique elements in the tuple. 

Method 6: using the built-in function set()

Using the built-in function set() to create a set of unique elements in the tuple and then using a list comprehension to count the frequency of each unique element:

Python3




test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
 
unique_elems = set(test_tup)
freq_dict = {elem: [x for x in test_tup].count(elem) for elem in unique_elems}
 
print("Tuple elements frequency is : " + str(freq_dict))


Output

Tuple elements frequency is : {4: 3, 5: 4, 6: 2}

Time complexity: O(n^2) due to the nested loop in the list comprehension, 
Auxiliary space: O(n) to store the dictionary. 

Method 7: Using reduce():

Algorithm:

  1. Import the required modules.
  2. Initialize a tuple with elements.
  3. Apply reduce() function on the tuple with Counter() function and Counter() function as the initial value.
  4. Print the result.

Python3




from collections import Counter
from functools import reduce
 
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Elements frequency in Tuple
# Using reduce() + Counter()
res = reduce(lambda x, y: Counter(x) + Counter(y), [test_tup], Counter())
 
# printing result
print("Tuple elements frequency is : " + str(res))
 
#This code is contrinuted by Pushpa.


Output

The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : Counter({5: 4, 4: 3, 6: 2})

Time Complexity:
The time complexity of this code is O(nlogn) because sorting is required for tuples and dictionaries, and dictionaries are used by the Counter() function.

Auxiliary Space:
The space complexity of this code is O(n) because additional space is used to store the output.

Method 8: Using numpy:

  1. Import the numpy module.
  2. Initialize a tuple test_tup with some values.
  3. Convert the tuple to a numpy array using np.array().
  4. Use np.unique() function to get the unique elements in the numpy array and their corresponding counts using the return_counts=True parameter.
  5. Use the zip() function to combine the two arrays into a dictionary, which is stored in the freq_dict variable.
    Print the dictionary freq_dict.

Python3




import numpy as np
 
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
 
# convert tuple to numpy array
arr = np.array(test_tup)
 
# calculate frequency of each element
unique, counts = np.unique(arr, return_counts=True)
freq_dict = dict(zip(unique, counts))
 
# print result
print("Tuple elements frequency is : " + str(freq_dict))
#This code is contributed by Vinay Pinjala


Output:
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}

Time complexity: O(n log n).
Auxiliary Space: O(n)\



Similar Reads

Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Python - Elements Frequency in Mixed Nested Tuple
Sometimes, while working with Python data, we can have a problem in which we have data in the form of nested and non-nested forms inside a single tuple, and we wish to count the element frequency in them. This kind of problem can come in domains such as web development and Data Science. Let's discuss certain ways in which this task can be performed
8 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. Input : test_list = [[(4, 5), (3, 2)], [(2, 2)]] Outp
5 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Practice Tags :