n
smaller lists.math.ceil()
and len()
to get the size of each chunk.list()
and range()
to create a new list of size n
.map()
to map each element of the new list to a chunk the length of size
.from math import ceil def chunk_into_n(lst, n): size = ceil(len(lst) / n) return list( map(lambda x: lst[x * size:x * size + size], list(range(n))) )
chunk_into_n([1, 2, 3, 4, 5, 6, 7], 4) # [[1, 2], [3, 4], [5, 6], [7]]
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️