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 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) |
chevron_right
filter_none
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 # 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) |
chevron_right
filter_none
Output:
Counter({('hi', 'bye'): 2, ('a', 'b'): 2, ('Geeks', 'forGeeks'): 1})
Recommended Posts:
- Python | Remove duplicate tuples from list of tuples
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Find the tuples containing the given element from a list of tuples
- Python | Remove tuples from list of tuples if greater than n
- Python | Combining tuples in list of tuples
- Python | Program to count duplicates in a list of tuples
- Python | Min and Max value in list of tuples
- Python | Unzip a list of tuples
- Python | Group tuples in list with same first value
- Python | Get unique tuples from list
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Preceding element tuples in list
- Python | Convert a list of Tuples into Dictionary
- Python | List of tuples to dictionary conversion
- Python | Merge two lists into list of tuples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



