Break an iterable into N-length chunks
I'd like you to write a function that accepts a sequence and a number n
and returns one list-of-lists containing lists of size n.
It should work something like this:
>>> for chunk in chunked([1, 2, 3, 4, 5], n=2):
... print(*chunk)
...
1 2
3 4
5
>>> for chunk in chunked(range(10), 4):
... print(tuple(chunk))
...
(0, 1, 2, 3)
(4, 5, 6, 7)
(8, 9)
Try to solve this exercise without using any third-party libraries (without using more-itertools or boltons for example).
Before attempting any bonuses, I'd like you to put some effort into figuring out the clearest and most idiomatic way to solve this problem.
Bonus 1
This is just a preview of the problem statement.
This exercise includes 3 bonuses and 9 hint links.
To solve this exercise, sign in to your Python Morsels account.
My name is Trey Hunner and I hold Python trainings for teams. I've spent countless hours refining my most interesting Python exercises into Python Morsels, a Python skill-building platform for folks who already know Python. Python Morsels is design to help you deepen your Python skills every week.
Sign up for Python Morsels to access this exercise and many more.
Join Python Morsels ✨