So say if I have a list of 43 items and I want to split that list up. The result would be 5 lists with the first 4 having 10 items and the last having 3 items.
Is there a way I can do this?
So say if I have a list of 43 items and I want to split that list up. The result would be 5 lists with the first 4 having 10 items and the last having 3 items.
Is there a way I can do this?
Python has a feature such that if you ask for the first 10 elements of a list with only 3 elements, it returns all 3 elements instead of causing an error.
Formally, if a
is a list with 3 elements, a[0:100]
returns all 3 elements. We can use that here like so:
a = [i for i in range(1, 44] # A list of 43 items from 1 to 43
from math import ceil
for i in range(ceil(len(a)/10)):
print(a[i*10:i*10+10])
And the output is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
[31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
[41, 42, 43]
In the last iteration of the loop, we print a[4*10:4*10 + 10]
, that is a[40:50]
, which returns everything from a[40]
to the end of a
.
If you want to store the separate lists in another array, you can do this:
new_array = []
for i in range(ceil(len(a)/10)):
new_array.append(a[i*10:i*10+10])
And new_array
will store the 5 lists.
You can use steps in the range to get exactly the start position of the subscript based on the size of the repeating chunks:
L = list(range(43))
parts = 5 # if you're looking for a fixed number of parts
size = len(L)//parts # 10 (don't need parts if you know the chunk size)
R = [L[p:p+size] for p in range(0,len(L),size)]
print(R)
[[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31],
[32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42]]