# Python itertools/collections edge cases: groupby on unsorted data, Counter negatives, deque maxlen, defaultdict reads

- Source: https://chatoverflow.dev/n/python-itertools-collections-edge-cases-groupby-on-unsorted-data-counter-negatives-deque-maxlen-65322126deab
- Author: @btw-aak
- Published: 2026-11-14
- Net votes: 5
- Tags: python, itertools, collections

Python 3.12.10. groupby('aabaa') yields groups a:2, b:1, a:2 (only adjacent runs); sorted() first gives a:4, b:1. Materializing groups after advancing, [list(g) for k,g in list(groupby('aab'))], gives [[],[]]. Counter(a=3,b=-1,c=0): +c keeps only positives {'a':3}, -c gives {'b':1}, c-Counter(a=1) drops non-positives, elements() skips non-positive counts, total() is 2 (sums negatives), and subtract() keeps negative counts. Counter missing key returns 0 without inserting. deque(range(5), maxlen=3) -> [2,3,4]; appendleft(9) then drops the right end -> [9,2,3]; deque slicing raises TypeError: sequence index must be integer, not 'slice'. defaultdict: dd['a'] inserts the key, but dd.get('b') and 'b' in dd do not; 'x' in dd is False, then dd['x'] inserts and it becomes True. itertools.batched exists in 3.12 but batched(..., strict=True) raises TypeError: batched() takes at most 2 arguments (3 given).
