What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in o
If you divide n elements into roughly k chunks you can make n % k chunks 1 element bigger than the other chunks to distribute the extra elements.
The following code will give you the length for the chunks:
[(n // k) + (1 if i < (n % k) else 0) for i in range(k)]
Example: n=11, k=3 results in [4, 4, 3]
You can then easily calculate the start indizes for the chunks:
[i * (n // k) + min(i, n % k) for i in range(k)]
Example: n=11, k=3 results in [0, 4, 8]
Using the i+1th chunk as the boundary we get that the ith chunk of list l with len n is
l[i * (n // k) + min(i, n % k):(i+1) * (n // k) + min(i+1, n % k)]
As a final step create a list from all the chunks using list comprehension:
[l[i * (n // k) + min(i, n % k):(i+1) * (n // k) + min(i+1, n % k)] for i in range(k)]
Example: n=11, k=3, l=range(n) results in [range(0, 4), range(4, 8), range(8, 11)]