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