Python | Tuple Column element frequency
Last Updated :
12 May, 2023
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 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
# Tuple Column element frequency
# using map() + count()
# initializing list of tuples
test_list = [(1, 'Geeks'), (2, 'for'), (3, 'Geeks')]
# printing the original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# using map() + count()
# Tuple Column element frequency
res = list(map(lambda i: i[K], test_list)).count('Geeks')
# printing result
print("The frequency of element at Kth index is : " + str(res))
Output : The original list is : [(1, 'Geeks'), (2, 'for'), (3, 'Geeks')]
The frequency of element at Kth index is : 2
Time complexity: O(n),
Auxiliary space: O(1).
Method #2: Using Counter() + list comprehension
List comprehension performs the task of getting the Kth element of the tuples and the counting part is handled by Counter function of collection library.
Python3
# Python3 code to demonstrate
# Tuple Column element frequency
# using Counter() + list comprehension
from collections import Counter
# initializing list of tuples
test_list = [(1, 'Geeks'), (2, 'for'), (3, 'Geeks')]
# printing the original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# using Counter() + list comprehension
# Tuple Column element frequency
res = Counter(i[K] for i in test_list)
# printing result
print("The frequency of element at Kth index is : " + str(res['Geeks']))
Output : The original list is : [(1, 'Geeks'), (2, 'for'), (3, 'Geeks')]
The frequency of element at Kth index is : 2
Time complexity: O(n), where n is the length of the input list.
Space complexity: O(k), where k is the number of unique elements at the Kth index of the input list.
Method 3: Iterative using loop
using a simple for loop to iterate through the list of tuples and maintain a dictionary to keep track of the frequency of elements at Kth index.
Python3
# initializing list of tuples
test_list = [(1, 'Geeks'), (2, 'for'), (3, 'Geeks')]
# initializing K
K = 1
# using for loop to count frequency
freq_dict = {}
for tup in test_list:
if tup[K] in freq_dict:
freq_dict[tup[K]] += 1
else:
freq_dict[tup[K]] = 1
# printing result
print("The frequency of element at Kth index is :", freq_dict['Geeks'])
OutputThe frequency of element at Kth index is : 2
Time complexity: O(n), where n is the length of the list of tuples.
Auxiliary space: O(k), where k is the number of distinct elements at Kth index.
Method 4: Use defaultdict from collections module
Stepwise Approach:
- Import the defaultdict module from collections.
- Initialize a defaultdict with an integer as the default value. This means that when a key is not present in the dictionary, it will be assigned a default value of 0.
- Loop through the tuples in the test_list.
- For each tuple, access the element at the Kth index and increment its count in the defaultdict.
- Print the frequency of the element at the Kth index.
Python3
from collections import defaultdict
# initializing list of tuples
test_list = [(1, 'Geeks'), (2, 'for'), (3, 'Geeks')]
# initializing K
K = 1
# using defaultdict to count frequency
freq_dict = defaultdict(int)
for tup in test_list:
freq_dict[tup[K]] += 1
# printing result
print("The frequency of element at Kth index is :", freq_dict['Geeks'])
OutputThe frequency of element at Kth index is : 2
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), since we are creating a dictionary with n unique keys.
Method 5: Use the groupby function from the itertools module.
Steps:
- Import groupby function from itertools module
- Sort the list of tuples based on the element at the Kth index
- Use groupby function to group the tuples based on the element at the Kth index
- Create a dictionary comprehension to count the frequency of each group
- Finally, print the frequency of the element at the Kth index
Python3
from itertools import groupby
# Initializing list of tuples
test_list = [(1, 'Geeks'), (2, 'for'), (3, 'Geeks')]
# Initializing K
K = 1
# sorting the list of tuples based on Kth index
sorted_list = sorted(test_list, key=lambda x: x[K])
# Grouping tuples based on Kth index
# using groupby() function
grouped = groupby(sorted_list, key=lambda x: x[K])
# Counting the frequency of each group
# using dictionary comprehension
freq_dict = {key: len(list(group)) for key, group in grouped}
# Printing result
print("The frequency of element at Kth index is:", freq_dict['Geeks'])
OutputThe frequency of element at Kth index is: 2
Time complexity: O(nlogn) due to the sorting operation, where n is the length of the input list of tuples.
Auxiliary space: O(n) due to the creation of the sorted list and dictionary.
Similar Reads
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 - 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
Python | Counting Nth tuple element
Sometimes, while working with Python, we can have a problem in which we need to count the occurrence of a particular's elements. This kind of problem is quite common while working with records. Let's discuss a way in which this task can be performed. Method #1 : Using Counter() + generator expressio
5 min read
Python - Count elements in tuple list
Sometimes, while working with data in form of records, we can have a problem in which we need to find the count of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method #1: Using len()
5 min read
Python - Count elements in record tuple
Sometimes, while working with data in form of records, we can have a problem in which we need to find the total element counts of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method
5 min read
Python - Similar Consecutive elements frequency
Sometimes, while working with Python, we can have a problem in which we have to find the occurrences of elements that are present consecutively. This problem have usage in school programming and data engineering. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop
5 min read
Python | Column Mean in tuple list
Sometimes, while working with records, we can have a problem in which we need to average all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using sum() + l
4 min read
Sort List Elements by Frequency - Python
Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"] then the output should be: ['Aryan'
3 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 discus
8 min read
Python - Get Nth column elements in Tuple Strings
Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
8 min read