0

How to split a list in a list of x lists in python ?

Exemple with list splited in 2 lists:

elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-> ([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])

Exemple with list splited in 3 lists (note the third list of tuple, containing "division rest"):

elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-> ([0, 1, 2], [3, 4, 5], [6, 7, 8, 9])

etc ...

bux
  • 7,087
  • 11
  • 45
  • 86
  • Or, read the `grouper` recipe on [itertools](https://docs.python.org/2/library/itertools.html). – kojiro Aug 20 '14 at 18:44
  • are you trying to split the original list into a tuple of lists or a list of lists? your examples show a tuple but the question is a little unclear – elrobe Aug 20 '14 at 18:46
  • the module `more_itertools` has `more_itertools.divide(n, iterable)`, which splits the the elements from iterable into n parts, maintaining order. One difference to the requirements from the question is that the remainder/s are added to the first 'sublists'. Second could be that it returns a list of generators. So do the following to get a list of lists `children = divide(3, [1, 2, 3, 4, 5, 6, 7])` followed `list(c) for c in children]` – Moritz Mar 02 '18 at 15:39

2 Answers2

2

You may try like this:

EDIT2:-

i,j,x=len(seq),0,[]

for k in range(m):

    a, j = j, j + (i+k)//m

    x.append(seq[a:j])

return x

Call like

seq = range(11), m=3

Result

result : [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]


def chunks(l, n):
    return [l[i:i + n] for i in range(0, len(l), n)]

EDIT1:-

>>> x = [1,2,3,4,5,6,7,8,9]
>>> zip(*[iter(x)]*3)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1
def chunk(iterable ,n):
    le = len(iterable)
    if n > le:
        return  iterable
    mo = le % n # get mod from length of the iterable % required len sublists 
    diff = le - mo #  if there was any mod, i.e 10 % 3 = 1, diff will be 9
    sli = le / n
    res = [iterable[ind:ind + sli] for ind in range(0, diff, sli)]
    res[-1] = res[-1] + iterable[diff:] # add from diff to end of the last sublist
    return tuple(res) # return a tuple lists

If mo = le % n == 0 diff will be equal to the length of the list so iterable[diff:] will add nothing.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321