Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count the most common items with Counter

Use collections.Counter to find the top-N most frequent items in a list, with deterministic tie-breaking.

Python practice15 minModules & Standard LibraryIntermediateLast updated March 23, 2026

Problem statement

Given a list of hashable items and an integer n, return a list of up to n tuples (item, count) representing the most common items. Sort results by frequency (highest first). When two items have the same frequency, sort them by the item value (ascending) to keep ordering deterministic.

Task

Implement a function most_common(items, n) that returns the top n items and their counts, sorted by count descending and then item ascending for ties.

Examples

Basic frequency count

Input

most_common(['apple', 'banana', 'apple'], 2)

Output

[('apple', 2), ('banana', 1)]

apple appears twice and banana once; we return the top 2 items.

Input format

A list of hashable items and an integer n.

Output format

A list of tuples [(item, count), ...] of length up to n.

Constraints

0 <= n. Items are hashable. Do not use print; return the result. Tie-breaking: when counts are equal, sort by item (ascending).

Samples

Sample 1

Input

most_common([1, 2, 2, 3], 10)

Output

[(2, 2), (1, 1), (3, 1)]

n is larger than distinct items, so return all items sorted by count then item.