Range with repeated consecutive numbers

  • A+
Category:Languages

I would like to create a range (e.g. (1, 5)) of numbers with some repetitions (e.g. 4):

[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4] 

One way would be to write:

list(itertools.chain(*([x] * 4 for x in range(1, 5)))) 

Or similarly:

list(itertools.chain(*(itertools.repeat(x, 4) for x in range(1, 5)))) 

However, there is a flatting step, which could be avoided.

Is there a more pythonic or more compact version to generate such a sequence?

 


You can just use a list comprehension.

l = [i for i in range(1, 5) for _ in range(4)] 

Output

[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: