Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop product in Python, we use nested lists and have several queries about how to find count of unique tuples. Let’s see how to get count of unique tuples in given list of tuples.
Below are some ways to achieve the above task.
Method #1: Using Iteration
# Python code to count unique # tuples in list of list import collections Output = 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
# 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})
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


