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
Python3
# Python code to count unique# tuples in list of listimport collectionsOutput = collections.defaultdict(int)# List initializationInput = [[('hi', 'bye')], [('Geeks', 'forGeeks')], [('a', 'b')], [('hi', 'bye')], [('a', 'b')]]# Using iterationfor elem in Input: Output[elem[0]] += 1 # Printing outputprint(Output) |
Output:
defaultdict(<class 'int'>, {('Geeks', 'forGeeks'): 1, ('hi', 'bye'): 2, ('a', 'b'): 2})Method #2: Using chain and Counter
Python3
# Python code to count unique# tuples in list of list# Importingfrom collections import Counterfrom itertools import chain# List initializationInput = [[('hi', 'bye')], [('Geeks', 'forGeeks')], [('a', 'b')], [('hi', 'bye')], [('a', 'b')]]# Using counter and chainOutput = Counter(chain(*Input))# Printing outputprint(Output) |
Output:
Counter({('hi', 'bye'): 2, ('a', 'b'): 2, ('Geeks', 'forGeeks'): 1})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') occures",len(x),"times") |
Output
tuple ('a', 'b') occures 2 timesMethod #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') occures",len(x),"times") |
Output
tuple ('a', 'b') occures 2 timesMethod #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') occures",len(x),"times") |
Output
tuple ('a', 'b') occures 2 timesMethod #6: Using only Counter function
Python3
from collections import CounterInput = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]check_ele=('a', 'b')x=Counter(Input)print("tuple ('a', 'b') occures",x[check_ele],"times") |
Output
tuple ('a', 'b') occures 2 timesMethod #7: Using countof function
Python3
import operator as opInput = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]check_ele=('a', 'b')print(op.countOf(Input,check_ele)) |
Output
2


