Open In App

Python | Tuple Column element frequency

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

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


Output

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

  1. Import the defaultdict module from collections.
  2. 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.
  3. Loop through the tuples in the test_list.
  4. For each tuple, access the element at the Kth index and increment its count in the defaultdict.
  5. 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'])


Output

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

  1. Import groupby function from itertools module
  2. Sort the list of tuples based on the element at the Kth index
  3. Use groupby function to group the tuples based on the element at the Kth index
  4. Create a dictionary comprehension to count the frequency of each group
  5. 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'])


Output

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads