Python | Count tuples occurrence in list of tuples
Last Updated :
01 Jun, 2023
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
Python3
# Python code to count unique
# tuples in list of list
import collections
Output = collections.defaultdict(int)
# List initialization
Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],
[('a', 'b')], [('hi', 'bye')], [('a', 'b')]]
# Using iteration
for elem in Input:
Output[elem[0]] += 1
# Printing output
print(Output)
Output:defaultdict(<class 'int'>, {('Geeks', 'forGeeks'): 1, ('hi', 'bye'): 2, ('a', 'b'): 2})
Time complexity: O(n), where n is the total number of tuples in the list of lists.
Auxiliary space: O(m), where m is the total number of unique tuples in the list of lists.
Method #2: Using chain and Counter
Python3
# Python code to count unique
# tuples in list of list
# Importing
from collections import Counter
from itertools import chain
# List initialization
Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],
[('a', 'b')], [('hi', 'bye')], [('a', 'b')]]
# Using counter and chain
Output = Counter(chain(*Input))
# Printing output
print(Output)
Output:Counter({('hi', 'bye'): 2, ('a', 'b'): 2, ('Geeks', 'forGeeks'): 1})
Time complexity: O(n), where n is the total number of tuples in the input list of lists.
Auxiliary space: O(n), as we are using a Counter object to store the counts of each unique tuple, which can take up to n space in the worst case.
Method #3: List Comprehension method
Python3
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=[i for i in Input if i==check_ele]
print("tuple ('a', 'b') occurs",len(x),"times")
Outputtuple ('a', 'b') occurs 2 times
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(k), where k is the number of occurrences of the check element in the input list.
Method #4: Using enumerate function
Python3
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=[i for a,i in enumerate(Input) if i==check_ele]
print("tuple ('a', 'b') occurs",len(x),"times")
Outputtuple ('a', 'b') occurs 2 times
Time complexity: O(n), where n is the length of the input list 'Input'.
Auxiliary space: O(m), where m is the number of occurrences of the tuple 'check_ele' in the input list 'Input'
Method #5: Using lambda function
Python3
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=list(filter(lambda i:(i==check_ele),Input))
print("tuple ('a', 'b') occurs",len(x),"times")
Outputtuple ('a', 'b') occurs 2 times
Time complexity: O(n), where n is the number of tuples in the Input list.
Auxiliary space: O(1) because it uses only a constant amount of extra space to store the filtered list and the length of that list.
Method #6: Using only Counter function
Python3
from collections import Counter
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=Counter(Input)
print("tuple ('a', 'b') occurs",x[check_ele],"times")
Outputtuple ('a', 'b') occurs 2 times
Time complexity: O(n), where n is the number of tuples in the Input list.
Auxiliary space: O(n), where n is the number of tuples in the Input list.
Method #7: Using countof function
Python3
import operator as op
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
print(op.countOf(Input,check_ele))
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), because the list comprehension creates a new list of all occurrences of the check_ele tuple.
Method #8: Using dict() method
Creating empty dictionary and iterating every element in list. Checking if element in dictionary increment value of key i by 1 else assign the key to element i with 1. finally, the dictionary will have keys as elements and their values as count of element in list.
Python3
#Initializing tuples in a list
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
#creating empty dictionary
count_tuples=dict()
#using for loop to iterate every value in Input
for i in Input:
if i not in count_tuples: #checking if element i present in dictionary or not
count_tuples[i]=1
else:
count_tuples[i]+=1
#printing dictionary of elements and their count
print(count_tuples)
Output{('hi', 'bye'): 2, ('Geeks', 'forGeeks'): 1, ('a', 'b'): 2}
Time complexity: O(n), where n is the length of the input list. The for loop iterates over every element in the input list exactly once.
Auxiliary space: O(m), where m is the number of unique tuples in the input list. In the worst case, when all the tuples are unique, the dictionary will contain m key-value pairs.
Method #9: Using map() function and tuple() constructor
This method involves mapping each list of tuples to a tuple of tuples and then counting the occurrences of each tuple in the list.
Python3
# Python code to count unique
# tuples in list of list
# List initialization
Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],
[('a', 'b')], [('hi', 'bye')], [('a', 'b')]]
# Using map() function and tuple() constructor
Output = {}
for elem in Input:
t = tuple(map(tuple, elem))
Output[t] = Output.get(t, 0) + 1
# Printing output
print(Output)
Output{(('hi', 'bye'),): 2, (('Geeks', 'forGeeks'),): 1, (('a', 'b'),): 2}
Time Complexity: O(nk), where n is the number of elements in the input list and k is the maximum number of tuples in a sublist.
Auxiliary Space: O(n), where n is the number of elements in the input list.
Method #10: Using set() and count()
- Initializes a list of tuples input_list containing five tuples.
- Converts the list to a set unique_set to remove duplicate tuples.
- Creates a dictionary output_dict where each key is a unique tuple from input_list, and each value is the count of that tuple in input_list.
- Prints the dictionary output_dict.
Python3
# Initializing tuples in a list
input_list = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
# Converting list to set to remove duplicates
unique_set = set(input_list)
# Counting occurrences of each unique tuple
output_dict = {elem: input_list.count(elem) for elem in unique_set}
# Printing output
print(output_dict)
Output{('a', 'b'): 2, ('hi', 'bye'): 2, ('Geeks', 'forGeeks'): 1}
The time complexity is O(n^2)
The auxiliary space is also O(n^2)
Similar Reads
Python - Occurrence counter in List of Records
Sometimes, while dealing with records we can have a problem in which we need count the occurrence of incoming digits corresponding to different characters/players in a game and compile them in a dictionary. This can have application in gaming and web development. Lets discuss a way in which this can
2 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
7 min read
Python - Convert List of Lists to Tuple of Tuples
Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let us discuss certain ways in which this task can be per
8 min read
Python | Count occurrence of all elements of list in a tuple
Given a tuple and a list as input, write a Python program to count the occurrences of all items of the list in the tuple. Examples: Input : tuple = ('a', 'a', 'c', 'b', 'd') list = ['a', 'b'] Output : 3 Input : tuple = (1, 2, 3, 1, 4, 6, 7, 1, 4) list = [1, 4, 7] Output : 6 Approach #1 : Naive Appro
5 min read
Element Occurrence in Dictionary of List Values - Python
We are having a dictionary of list we need to find occurrence of all elements. For example, d = {'a': [1, 2, 3, 1], 'b': [3, 4, 1], 'c': [1, 5, 6]} we need to count the occurrence of all elements in dictionary list so that resultant output should be {'a': 2, 'b': 1, 'c': 1}.Using a Dictionary Compre
3 min read
Count Occurance of Substring in a List of Strings - Python
To count the occurrences of a particular substring in a list of strings in Python, we can use several methods. In this article, we are going to explore different methods to count the existence of a particular substring in a given list.Using sum() and Generator ExpressionThis method uses a generator
2 min read
Python | Count String occurrences in mixed list
Sometimes, while working with data, we can have a problem in which we need to check for the occurrences of a particular data type. In this, we can also have a problem in which we need to check for string occurrences. Let's discuss certain ways in which this task can be performed. Method #1 : Using i
8 min read
Generating a "Set Of Tuples" from A "List of Tuples" - Python
We are given a list of tuples and we need to extract only the unique tuples while removing any duplicates. This is useful in scenarios where you want to work with distinct elements from the list. For example:We are given this a list of tuples as [(1, 2), (3, 4), (1, 2), (5, 6)] then the output will
3 min read
Python | Extend tuples by count of elements in tuple
Sometimes, while working with data, we can have an application in which we need to duplicate tuple elements by the amount of element count. This is very unique application but can occur in certain cases. Let's discuss certain ways in which this task can be performed. Method #1: Using nested loops Th
6 min read
Python - Sum of each List element occurrence in another
Sometimes, while working with Python, we can have a problem in which we need to get occurrence of 1 element in another. But as a modification of this, we can have a problem in which we need to count the occurrence of all elements of 1 list in another. Lets discuss certain ways in which this task can
6 min read