Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+5 votes
7 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?

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

2 Answers

+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 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
asked Jan 14, 2020 in Python by Rajesh Malhotra (19.9k points)
+1 vote
2 answers
+3 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...