7 views
in Python
edited

In a list with range(1,16) and I am trying to divide this list in some fixed numbe n . Let's assume n=7

```>>> y
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,]
>>> k = [ y [o:p + 7] for o in range(0, len(y), 7) ]
>>> k
[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15]]```

Now I want to split this list in such a manner that I get n chunks even/uneven, How can I do that?

If you are looking for upskilling yourself in python you can join our Python Certification and learn from an industry expert.

+1 vote
by (46k points)
edited by

There are many methods to do it, but I'll suggest you to use more_itertools.divide

Syntax:

import more_itertools as mit

iterable = range(1, 16)
[list(c) for c in mit.divide(7, iterable)]

Output:

[[ 1,  2,  3,  4, 5, 6],
[ 7,  8,  9,  10],
[11, 12, 13, 14],

+1 vote
by (32.3k points)
edited

You can simply use numpy:

>>> import numpy

>>> x = range(15)

>>> l = numpy.array_split(numpy.array(x),7)

You can use the following video tutorials to clear all your doubts:-