Search code examples
pythonlistloops

How to store numbers in chunks from a List and create another List?


I have two Lists x and y:

x = [2 3 1 1 2 5 7 3 6]
y = [0 0 4 2 4 5 8 4 5 6 7 0 5 3 2 8 1 3 1 0 4 2 4 5 4 4 5 6 7 0]

I want to create a list "z" and want to store group/chunks of numbers from y into z and the size of groups is defined by the values of x.

so z store numbers as

z = [[0,0],[4,2,4],[5],[8],[4,5],[6,7,0,5,3],[2,8,1,3,1,0,4],[2,4,5],[4,4,5,6,7,0]]

I tried this loop:

h=[]
for j in x:
    h=[[a] for i in range(j) for a in y[i:i+1]]

But it is only storing for last value of x. Also I am not sure whether the title of this question is appropriate for this problem. Anyone can edit if it is confusing. Thank you so much.


Solution

  • You're reassigning h each time through the loop, so it ends up with just the last iteration's assignment.

    You should append to it, not assign it.

    start = 0
    for j in x:
        h.append(y[start:start+j])
        start += j