+5 votes
4 views
in Python by (3.5k points)
edited by

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?

2 Answers

+1 vote
by (46.1k 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 (31.4k points)
edited by

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:-

Related questions

0 votes
1 answer
+1 vote
2 answers
+3 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...