I worked in Python 3.6, and I am a beginner. So can anyone give me a true way of how can slice a list into variable size sub-list. I tried this solution from this site, but it gave me fixed size of sliced list. To clarify:
if I have this list:
inputList= [0,1,2,3,4,5,6,7]
I want the output to be like e.g.:
outputList=[[0,1,2], [3,4], [5], [6,7]]
each time it depends on (for example) user input or some variable size.
Just use
itertools.islice(). This has the added advantage that if you request a slice that you would normally take you out of bounds, you won't get an error. You'll just get as many items are left as possible.For example, if you had
slices = (3, 2, 1, 3, 2), your result would be[[0, 1, 2], [3, 4], [5], [6, 7], []].Basically,
iter(input_list)creates an iterable of your list so you can fetch the nextkvalues withislice().