750 B
750 B
title, type, language, tags, cover, dateModified
| title | type | language | tags | cover | dateModified | |
|---|---|---|---|---|---|---|
| Split list into n chunks | snippet | python |
|
succulent-10 | 2020-10-23T05:35:06+03:00 |
Chunks a list into n smaller lists.
- Use
math.ceil()andlen()to get the size of each chunk. - Use
list()andrange()to create a new list of sizen. - Use
map()to map each element of the new list to a chunk the length ofsize. - If the original list can't be split evenly, the final chunk will contain the remaining elements.
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]]