Python Practice › Iterator & Generator Programs › Program 11
Split a list into chunks
Write a generator that yields chunks of a given size.
Input
1..10, size 3
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
Approach
- Slice from each start index.
Solution
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.