Python – How to Split List into Sublists by Number of Elements

listpythonsplit

In python, if I have the list of elements

l = ['a', 'b', 'c', 'd', 'e', 'f']

and a list of numbers

n = [2, 1, 3]

How I can split the list l by the numbers in n ?

And get this list of lists

[['a', 'b'], ['c'], ['d', 'e', 'f']]

Best Answer

You could use islice:

>>> from itertools import islice
>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>> n = [2, 1, 3]
>>> it = iter(l)
>>> out = [list(islice(it, size)) for size in n]
>>> out
[['a', 'b'], ['c'], ['d', 'e', 'f']]