Python Practice › Tuple Programs › Program 34
How often each tuple appears
Write a Python program to count how many times each tuple appears in a list.
Input
[("s", "q"), ("t", "o", "o", "l"), ("p", "y"), ("s", "q")]Output
{('s', 'q'): 2, ('t', 'o', 'o', 'l'): 1, ('p', 'y'): 1}Approach
- Tuples are hashable, so
Countercounts them directly.
Solution
from collections import Counterdata = [("s", "q"), ("t", "o", "o", "l"), ("p", "y"), ("s", "q")]print(dict(Counter(data)))Output
{('s', 'q'): 2, ('t', 'o', 'o', 'l'): 1, ('p', 'y'): 1}Learn the concept
New to this topic? Read the lesson, then come back.