On this page
  1. collections.Counter
  2. Import
  3. Signature & Overview
  4. Methods & Attributes
  5. Usage
  6. Gotchas
  7. REPL Inspect

collections.Counter

Prev: collections.ChainMap | Up: collections | Next: collections.defaultdict
Rel: collections.ChainMap, collections.defaultdict, collections.deque, collections.namedtuple
Ref: docs.python.org — collections.Counter
Tags: #public #python3 #stdlib #collections


Import

import collections
from collections import Counter

Signature & Overview

collections.Counter(iterable=None, /, **kwds)

Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.

Methods & Attributes

Usage

from collections import Counter

counts = Counter("abracadabra")
assert counts["a"] == 5
assert counts["z"] == 0   # missing keys return 0 without inserting them
assert counts.most_common(2) == [("a", 5), ("b", 2)]

Gotchas

REPL Inspect

from collections import Counter
help(Counter)

Linked from

Related notes