Python snippets

A small personal collection of Python one-liners and helpers.

Flatten a nested list

flat = [x for row in rows for x in row]

Chunk an iterable

from itertools import islice

def chunks(it, n):
    it = iter(it)
    while batch := list(islice(it, n)):
        yield batch

Read a file lazily

with open(path, encoding="utf-8") as f:
    for line in f:
        handle(line.rstrip("\n"))

Timing a block

from time import perf_counter
t = perf_counter(); work(); print(f"{perf_counter() - t:.3f}s")