One liner function to spread python index list

Question:

I need a single line function to the following function:

Input =  [1, 3, 7, 9]
Output = [1,1,3,3,7,7,7,7,9,9]

The input string presents the indexes till which the index itself will appear.

So 1 will appear till 1st index (0th and 1st index in output)

3 will appear till 3rd index after the 1st index (2nd, 3rd index in output)

7 will appear till the 7th index after 3rd index (4th, 5th, 6th, and 7th index in output)

and so on till the last index…

What I thought I can do is the following:

count = 0
Output = []
for i in range(Input[-1]):
  Output.append(Input[count])
  if Input[count] == i:
    count++
return Output

But I feel this should be possible to be written in a single liner or a lambda function or something which looks much cleaner!
Also apologies if the title sounds different than what I am asking. Wasn’t able to find what I needed so linking any helpful answer would be grateful!

Asked By: Ojas Raundale

||

Answers:

Since these are also indices, use each number as start and end limits using zip().

[j for i, j in zip([-1]+Input, Input) for _ in range(i,j)]
Answered By: not a robot
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.