def chunked(items, n):
    if n <= 0:
        raise ValueError("n must be positive")
    it = iter(items)
    while True:
        chunk = []
        for _ in range(n):
            try:
                chunk.append(next(it))
            except StopIteration:
                break
        if chunk:
            yield chunk
        else:
            break
