Iterators and generators: Python snippets
Part of 30 Seconds of Python. Source: snippets/iterators.py.
Every example below is run as a test.
take
First n items of any iterable as a list.
def take(iterable, n):
return list(islice(iterable, n))
>>> take(count(10), 3)
[10, 11, 12]
batched
Yield tuples of up to n items (itertools.batched exists in 3.12+).
def batched(iterable, n):
if n < 1:
raise ValueError('n must be >= 1')
it = iter(iterable)
while chunk := tuple(islice(it, n)):
yield chunk
>>> list(batched('ABCDEFG', 3))
[('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
pairwise
Consecutive overlapping pairs (itertools.pairwise exists in 3.10+).
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
>>> list(pairwise([1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
interleave
Round-robin items from several iterables until all are exhausted.
def interleave(*iterables):
iterators = [iter(it) for it in iterables]
while iterators:
alive = []
for it in iterators:
try:
yield next(it)
alive.append(it)
except StopIteration:
pass
iterators = alive
>>> list(interleave('AB', '1234', 'x'))
['A', '1', 'x', 'B', '2', '3', '4']
run_length
Run-length encode: (value, count) for each run of equal values.
def run_length(iterable):
return [(k, sum(1 for _ in g)) for k, g in groupby(iterable)]
>>> run_length('aaabccdddd')
[('a', 3), ('b', 1), ('c', 2), ('d', 4)]
flatten_iter
Lazily chain an iterable of iterables.
def flatten_iter(iterables):
return chain.from_iterable(iterables)
>>> list(flatten_iter([range(2), 'ab', (9,)]))
[0, 1, 'a', 'b', 9]
nth
The item at index n of any iterable, or default.
def nth(iterable, n, default=None):
return next(islice(iterable, n, None), default)
>>> nth((x * x for x in range(10)), 4), nth([], 2, 'missing')
(16, 'missing')
ilen
Count items of an iterator without building a list.
def ilen(iterable):
return sum(1 for _ in iterable)
>>> ilen(x for x in range(1000) if x % 7 == 0)
143
peek
Look at the first item and get back an iterator that still includes it.
def peek(iterable):
it = iter(iterable)
try:
head = next(it)
except StopIteration:
return None, iter(())
return head, chain([head], it)
>>> head, it = peek(iter([1, 2, 3]))
>>> head, list(it)
(1, [1, 2, 3])