Skip to content
Clean Code

Clean Code

Python Counter: Count Word Frequency in One Line Instead of Six

· Count words in Python with Counter | 6 lines ka kaam, 1 line mein

Three ways to count words in Python: an if/else dict loop (6 lines), dict.get() (3 lines) and collections.Counter (1 line). Same output every time, and most_common(1) gives the top word. A small clean code habit for more readable Python.

The code

v1
counts = {}
for w in words:
    if w in counts:
        counts[w] += 1
    else:
        counts[w] = 1
v2
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
v3
from collections import Counter
counts = Counter(words)
most
counts.most_common(1)
Interview SheetPractise the patterns behind interview problemsProblems grouped by pattern, each with the idea first and the code in four languages.