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