Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Chunk an iterable into fixed-size blocks

Split any iterable into consecutive fixed-size chunks. The last chunk may be smaller.

Python practice16 minModules & Standard LibraryIntermediateLast updated March 23, 2026

Problem statement

Write chunk_iterable(iterable, size) which takes any iterable and an integer chunk size > 0 and returns a list of lists. Each inner list should contain up to size elements, preserving the original order. The final chunk may have fewer than size elements if there aren't enough remaining. The function should accept any iterable (lists, strings, generators, range, etc.).

Task

Implement chunk_iterable(iterable, size) returning a list of lists, where each inner list is a chunk of up to size elements taken from the iterable in order.

Examples

Chunk a list

Input

chunk_iterable([1,2,3,4,5], 2)

Output

[[1, 2], [3, 4], [5]]

The list is split into chunks of size 2. The final chunk contains the leftover element.

Input format

Two arguments: an iterable and a positive integer size, e.g., chunk_iterable([1,2,3], 2)

Output format

A list of lists representing consecutive chunks

Constraints

- size is a positive integer (>=1). - Do not assume the input is a sequence; support any iterable. - Use only the Python standard library (itertools is allowed).

Samples

Sample 1

Input

chunk_iterable('abcdef', 3)

Output

[['a', 'b', 'c'], ['d', 'e', 'f']]

Strings are iterables; chunks are lists of characters.