1

I want to break a list into sub-lists of n elements. I could convert the list (after adding appropriate padding) to a numpy array, e.g.:

n = 20
L = [x for x in range(93)]
Lnp = np.array(L+[0]*7).reshape(-1,n)
Lgrouped = [g for g in Lnp]

enter image description here

but this is sub-optimal. What would be a good way to do this without numpy? (itertools comes to mind, but didn't seem to find a straightforward function...)

ntg
  • 12,950
  • 7
  • 74
  • 95
  • 2
    See the `grouper` function in the [Recipes](https://docs.python.org/2/library/itertools.html#recipes) section of the `itertools` documentation. – chepner Apr 10 '18 at 15:37

1 Answers1

2

This is a common chunking problem, I would use slicing in a list-comp:

[L[i:i+n] for i in range(0, len(L), n)]
#[[0,   1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
# [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
# [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
# [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
# [80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92]]
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54