Collections

Collections Module

collections provides specialized containers for common data shapes.

Use Counter when the question is "how many times did each value appear?"

Source

from collections import Counter

counts = Counter("banana")
print(counts.most_common(2))

Output

[('a', 3), ('n', 2)]
dequefast appends both endsCounterkey → countdefaultdictmissing key defaultnamedtupletuple with names
Four specialised containers for shapes the built-in types don't cover well: deque, Counter, defaultdict, namedtuple.

Use defaultdict(list) when each key gathers multiple values and the missing-key case should create an empty list automatically.

Source

from collections import defaultdict

groups = defaultdict(list)
for name, team in [("Ada", "red"), ("Grace", "blue"), ("Lin", "red")]:
    groups[team].append(name)
print(dict(groups))

Output

{'red': ['Ada', 'Lin'], 'blue': ['Grace']}

Use deque for queue operations at both ends, and namedtuple when a tiny immutable record needs names as well as positions.

Source

from collections import deque, namedtuple

queue = deque(["first"])
queue.append("second")
print(queue.popleft())

Point = namedtuple("Point", "x y")
print(Point(2, 3).x)

Output

first
2

Notes

See also

Run the complete example

Example code

Expected output

[('a', 3), ('n', 2)]
{'red': ['Ada', 'Lin'], 'blue': ['Grace']}
first
2

Execution time appears here after you run the example.