0

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]
Liondancer
  • 15,721
  • 51
  • 149
  • 255

1 Answers1

5

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)]
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111