collections — container datatypes

Python collections.Counter, defaultdict, and deque, including Counter subtraction and verified examples.

モジュールページの本文は現在英語です。

collections is a standard-library module. It is not a built-in, and it is not a third-party package. Import the types you need, for example `from collections import Counter, defaultdict, deque`.

This page covers the three types used most often for counting, default values, and queues. namedtuple, ChainMap, and the abstract base classes are documented officially and are omitted here.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

Counter

Counter is a dict subclass for counting hashable objects. Missing keys return 0 rather than raising KeyError. Subtracting one Counter from another keeps only positive counts.

Counter, most_common, and elements

Counter(iterable=None, **kwds)
Counter.most_common(n=None)
Counter.elements()

Count items from an iterable or from keyword counts. most_common(n) returns the n most frequent items; elements() repeats each item according to its count.

Returns: most_common() returns a list of (element, count) pairs. elements() returns an iterator. Counts of zero or less are ignored by elements().

  • Accessing a missing key returns 0 and does not insert the key.
  • update() adds counts. subtract() subtracts counts and may store zeros or negatives. The - operator keeps only positive results.
python
from collections import Counter

counts = Counter("abca")
print(counts)
print(counts["z"])
print(counts.most_common(2))
print(list(counts.elements()))
counts.subtract("aa")
print(dict(counts))

Expected output

Counter({'a': 2, 'b': 1, 'c': 1})
0
[('a', 2), ('b', 1)]
['a', 'a', 'b', 'c']
{'a': 0, 'b': 1, 'c': 1}

Official documentation →

Compare line counts with Counter

Counter.__sub__(other)

Counter subtraction keeps positive differences. Subtract in both directions to find excess lines in each input. This section keeps the original Python reference anchor.

  • A set drops duplicates. Use sets for membership and Counter for frequency.
  • This comparison ignores line order.
python
from collections import Counter

before = Counter(["apple", "apple", "pear"])
after = Counter(["apple", "pear", "pear"])
print("removed:", dict(before - after))
print("added:", dict(after - before))

Expected output

removed: {'apple': 1}
added: {'pear': 1}

Official documentation →

defaultdict

defaultdict is a dict subclass that calls a factory for missing keys. The factory is stored as default_factory. If default_factory is None, missing keys raise KeyError, like a normal dict.

defaultdict

defaultdict(default_factory=None, /[, ...])

A dict that inserts default_factory() when a missing key is first accessed.

ParameterDescription
default_factoryA zero-argument callable such as list, int, or set. None disables automatic insertion.
  • The factory is called with no arguments. It cannot see the missing key.
  • Using int as the factory produces a counter-like mapping, but Counter remains the clearer type for counting.
python
from collections import defaultdict

groups = defaultdict(list)
for name, city in [("Ada", "London"), ("Grace", "New York"), ("Alan", "London")]:
    groups[city].append(name)
print(dict(groups))
print(groups["Paris"])

Expected output

{'London': ['Ada', 'Alan'], 'New York': ['Grace']}
[]

Official documentation →

deque

deque is a double-ended queue with O(1) appends and pops on either side. A list can do cheap appends and pops on the right, but popping from index 0 is O(n).

deque

deque([iterable[, maxlen]])

A thread-safe, memory-efficient sequence with fast appends and pops from both ends.

ParameterDescription
iterableOptional items used to initialize the deque from left to right.
maxlenIf set, the deque discards items from the opposite end when it grows past this length.
python
from collections import deque

items = deque(["a", "b"], maxlen=3)
items.append("c")
items.appendleft("d")
print(list(items))
print(items.pop(), items.popleft())
print(list(items))

Expected output

['d', 'a', 'b']
b d
['a']

Official documentation →