How can I print chunks of size 5 from a list and the remaining tail end that does not have chunk size of 5
For example
a = list(range(23))
I want to produce print out
[0,1,2,3,4], [5,6,7,8,9], [10,11,12,13,14], [15,16,17,18,19], [20,21,22]
How can I print chunks of size 5 from a list and the remaining tail end that does not have chunk size of 5
For example
a = list(range(23))
I want to produce print out
[0,1,2,3,4], [5,6,7,8,9], [10,11,12,13,14], [15,16,17,18,19], [20,21,22]
from the itertools recipes:
from functools import partial
from itertools import islice
def take(n, iterable):
return tuple(islice(iterable, n))
def chunked(iterable, n):
return iter(partial(take, n, iter(iterable)), tuple())
a = list(range(23))
print(list(chunked(a, 5)))
# [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9), (10, 11, 12, 13, 14),
# (15, 16, 17, 18, 19), (20, 21, 22)]
or simply:
n = 5
[a[j:j+n] for j in range(0, len(a), n)]