Python Practice › Tuple Programs › Program 34

How often each tuple appears

EasyTuple Programs · 34 of 70

Write a Python program to count how many times each tuple appears in a list.

Advertisement
Input
[("s", "q"), ("t", "o", "o", "l"), ("p", "y"), ("s", "q")]
Output
{('s', 'q'): 2, ('t', 'o', 'o', 'l'): 1, ('p', 'y'): 1}

Approach

  1. Tuples are hashable, so Counter counts them directly.

Solution

Python
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}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More tuple programs

← All 70 Tuple Programs