Collections and itertools
Reuse standard-library tools for common collection operations.
On this page
The concept
Counter stores occurrence counts. defaultdict calls a factory to supply missing values, which is convenient for grouping. chain traverses several iterables as one stream; islice takes a portion from an iterator without requiring a complete intermediate list.
These are ready-made standard-library tools, not an introduction to defining classes. Understand the input and output contract before adopting one. In particular, itertools.groupby groups adjacent matching keys, not every matching item across an unsorted stream.
Worked example
from collections import Counter, defaultdict
from itertools import chain, islice
counts = Counter(["book", "pen", "book"])
print(counts.most_common())
groups = defaultdict(list)
for name, city in [("Sara", "Erbil"), ("Dana", "Duhok"), ("Avan", "Erbil")]:
groups[city].append(name)
print(dict(groups))
values = chain(range(3), range(10, 13))
print(list(islice(values, 4)))Trace the result
- Counter produces counts for book and pen.
- defaultdict(list) gives each city its own group list.
- chain joins two ranges and islice consumes only the first four values.
[('book', 2), ('pen', 1)]
{'Erbil': ['Sara', 'Avan'], 'Duhok': ['Dana']}
[0, 1, 2, 10]Line-by-line walkthrough
Line 1: from collections import Counter, defaultdict
Import Counter, defaultdict from collections. This supplies standard counting and grouping tools. The caller can now use the imported names directly.
Line 2: from itertools import chain, islice
Import chain, islice from itertools. This supplies composable iterator operations. The caller can now use the imported names directly.
Line 4: counts = Counter(["book", "pen", "book"])
Evaluate Counter(['book', 'pen', 'book']), then bind or update counts with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Line 5: print(counts.most_common())
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 6: groups = defaultdict(list)
Evaluate defaultdict(list), then bind or update groups with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Lines 7–8: for name, city in [("Sara", "Erbil"), ("Dana", "Duhok"), ("Avan", "Erbil")]:
Obtain each item from [('Sara', 'Erbil'), ('Dana', 'Duhok'), ('Avan', 'Erbil')] and bind it to (name, city) before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.
Line 8: groups[city].append(name)
Call groups[city].append to add one item to the existing list. This call may have an effect even when its return value is not assigned.
Line 9: print(dict(groups))
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 10: values = chain(range(3), range(10, 13))
Evaluate chain(range(3), range(10, 13)), then bind or update values with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Line 11: print(list(islice(values, 4)))
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Common mistake
Assuming groupby performs global grouping can split one logical group into several pieces. Sort appropriately or use dictionary grouping.