Search code examples
pythonarraysfor-loopindexingindices

Python append values to empty list by skipping values in between a list


Just a minimal example of what I want to achieve.

I have an array:

array = [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,....,1,2,3,4,5,6,7,8,9,10]

I would like to loop through this array and create a new array which looks like this:

new_array = [1,1,2,1,2,3,1,2,3,4,1,2,3,4,5,....,1,2,3,4,5,6,7,8,9,10]

i.e. loop through array a, get the first value (i.e. 1), then skip the remaining 9 values, then get the first and the second value (i.e. 1,2), then skip the remaining 8 values, and so on.

The idea I came up with was to create indices and use it in the following way:

In [1]: indices = np.arange(1,10,1)
Out[1]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])

new_array = []
for i in array:
    for a,b in zip(indices,range(10)):
        new_array.append(i[0:a]) # here I am including i[0:1], i[0:2] and so on 

So it loops through array and gets the first value, then skips the remaining 9 values, then gets the first two values and skips the remaining 8 values and so on.

But this doesn't seem to work. How can I achieve this ?


Solution

  • For a signle list you can also use list extension for this:

    list = [1,2,3,4,5,6,7,8,9,10]
    output = []
    i = 1
    while i <= 10:
        output.extend(list[0:i])
        i +=1
    
    print output
    

    For your list you can extend this to:

    list = [1,2,3,4,5,6,7,8,9,10]*10
    
    output = []
    
    i = 1
    j = 0
    k = 1
    while k <= 10:
       output.extend(list[j:i])
       j +=10
       k +=1
       i = j+k
    
    print output