Skip to the workspace
Pebellslearn by building

Python syntax & reference

Find the form you need, compare how it behaves, and open the complete explanation when you need more depth.

Python 3.10+ syntax; individual entries identify newer features. Browser exercises use the configured Python runner.

1 matching syntax entry

Counting and grouping

Learn in depth →

Counter counts hashable values; defaultdict creates a missing value when accessed with [].

Counter(iterable); defaultdict(factory)

Example

from collections import Counter, defaultdict
print(sorted(Counter("banana").items()))
groups = defaultdict(list)
groups["fruit"].append("pear")
print(dict(groups))

Result

[('a', 3), ('b', 1), ('n', 2)]
{'fruit': ['pear']}

Watch for: defaultdict.get does not invoke the factory. Counter entries may have zero or negative counts.

Practise this topic →
Complete explanation index (91 lessons indexed)

Collections: Counter, defaultdict, namedtuple, OrderedDict

Technical sources and review date

Original Pebells examples. Reviewed 2026-10-28.

Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.