Exercise · Modules, files and generators · lesson 11 of 12
Exercise: chunks
Write a generator chunks(items, size): a function with yield that gives out items in chunks — lists of size elements, order kept. items is any iterable: a list, a string, a range or another generator. The last chunk may be shorter.
list(chunks([1, 2, 3, 4, 5], 2))→[[1, 2], [3, 4], [5]]list(chunks([1, 2, 3], 10))→[[1, 2, 3]]list(chunks("abcde", 3))→[['a', 'b', 'c'], ['d', 'e']]next(chunks([7, 8, 9], 2))→[7, 8]
Constraints: size is an integer of at least 1; items may be empty, and then the generator gives out no chunks.
Do not add extra imports unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.