Split a list into chunks

EasyIterator & Generator Programs · 11 of 20

Write a generator that yields chunks of a given size.

Advertisement
Input
1..10, size 3
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Approach

  1. Slice from each start index.

Solution

Python
def chunks(items, size):    for i in range(0, len(items), size):        yield items[i:i + size] print(list(chunks(list(range(1, 11)), 3)))
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment