← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Counter

Topic: Data Structures

Advertisement

Introduction

Counter is a dict subclass for counting hashable objects, useful for frequency analysis.

Basic Counter

from collections import Counter

# From list
c = Counter(["a", "b", "a", "c", "a"])
print(c)  # Counter({'a': 3, 'b': 1, 'c': 1})

# From string
c = Counter("hello world")
print(c)  # Counter({'l': 3, 'o': 2, 'h': 1, ...})

# From dictionary
c = Counter({"a": 3, "b": 1})

Counter Methods

c = Counter([1, 2, 2, 3, 3, 3])

c.elements()          # Iterator over elements
c.most_common(2)      # Top 2 most common
c.most_common()       # All sorted by count
c.total()             # Sum of all counts

# Arithmetic
c1 = Counter([1, 2, 2])
c2 = Counter([2, 3, 3])
c1 + c2               # Counter addition
c1 - c2               # Subtraction (positive only)
c1 & c2               # Intersection (min)
c1 | c2               # Union (max)

Practice Problems

  1. Count character frequency in string
  2. Find most common words in text
  3. Compare two lists using Counter
  4. Create histogram with Counter
  5. Track letter occurrences in word

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →