1

For example if I have 2 lists:

list1 = [2,3]
list2 = [a,b,c,d,e]

The new list should become

newlist = [[a,b], [c,d,e]]

So the values of the first list make up the amount of values inside the nested lists.

David Buck
  • 3,752
  • 35
  • 31
  • 35
sannie
  • 11
  • 1
  • 2
    Yes, there is a way. What have you tried so far ? – IMCoins Nov 27 '19 at 13:54
  • Take a look at [this](https://stackoverflow.com/questions/36076154/how-to-divide-python-list-into-sublists-of-unequal-length) – Lukas Thaler Nov 27 '19 at 13:56
  • Couldn't add an answer in time but you can use `itertools.islice`: `it = iter(list2); newlist = [list(islice(it, n)) for n in list1]` – Jab Nov 27 '19 at 14:07
  • Just posted an answer to the referenced/dup question: https://stackoverflow.com/a/59072159/225020 – Jab Nov 27 '19 at 14:17

1 Answers1

2

What about this?

Code:

list1 = [2,3]
list2 = ['a','b','c','d','e']

rv = []
start = 0
for i in list1:
    rv.append(list2[start:start+i])
    start += i

Output:

>>> rv
[['a', 'b'], ['c', 'd', 'e']]
CDJB
  • 14,043
  • 5
  • 29
  • 55