Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Module collections

Provides specialized containers including Counter, deque and defaultdict.

Version: Python 3.14; repository image, production runtime not attested

Syntax

collections.Counter(iterable)

Provides specialized containers including Counter, deque and defaultdict.

A Counter lookup for an absent key yields zero without inserting it. A bounded deque drops the opposite end when append would exceed its limit.

The example counts event labels and retains only the last two.

Examples

import collections
events = ["A", "B", "A"]
counts = collections.Counter(events)
recent = collections.deque(maxlen=2)
for event in events:
    recent.append(event)
print(counts["A"], counts["Z"], "Z" in counts)
print(list(recent))

Result

2 0 False
['B', 'A']

The example counts event labels and retains only the last two.

Sources