1

I'm looking for a way to slice a list into n amount of sublists

So for example if

    A = [0,1,2,3,4,5,6,7,8,9]

If n = 4 I want 4 different sublists

    B = [0,1,2]
    C = [3,4,5]
    D = [6,7,8]
    E = [9]

but the last sublist must not be bigger than the previous so this wouldn't do

    B = [0,1]
    C = [2,3]
    D = [4,5]
    E = [6,7,8,9]
  • `[A[i:i+n] for i in range(0,len(A),n)]` with the length of the sub lists `n` being `math.ceil(len(A)/num_lists_wanted)` – dawg Nov 04 '16 at 00:22
  • @dawg yes but what this does with A only creates 3 sublists, `n` is the number of sublists and not the number of elements in each sublist. This only creates `B = [0,1,2,3] C = [4,5,6,7] D = [8,9]` theres no 4th sublist – NightmaresCoding Nov 04 '16 at 01:03
  • If I do `n=3; [A[i:i+n] for i in range(0,len(A),n)]` I get `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]` – dawg Nov 04 '16 at 01:11
  • @dawg thats not what i really wanted, that creates 4 sublists of 3 elements each. `n` doesnt represent the number of elements but the number of sublists so what i essencially needed is `n=3` and i get `[[0,1,2,3], [4,5,6,7], [8,9]]` cause then i have 3 sublists – NightmaresCoding Nov 04 '16 at 01:18
  • `len(A)/4` is 2.5; `math.ceil(2.5)` is 3 so if you want 4 sublists you would have `n=math.ceil(len(A)/4)` What am I missing? – dawg Nov 04 '16 at 01:24
  • @dawg got it alright thanks – NightmaresCoding Nov 04 '16 at 01:38
  • [Here](http://wordaligned.org/articles/slicing-a-list-evenly-with-python) what I was searching and was not able to find it duplicated questions: `def chunk(xs, n): '''Split the list, xs, into n evenly sized chunks''' L = len(xs) assert 0 < n <= L s, r = divmod(L, n) t = s + 1 return ([xs[p:p+t] for p in range(0, r*t, t)] + [xs[p:p+s] for p in range(r*t, L, s)])` Hope it would help someone (or even future me). – grundic Feb 21 '18 at 08:40

0 Answers0