Range with repeated consecutive numbers

You can just use a list comprehension instead.

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]

Nothing wrong with your solution. But you can use chain.from_iterable to avoid the unpacking step.

Otherwise, my only other recommendation is NumPy, if you are happy to use a 3rd party library.

from itertools import chain, repeat
import numpy as np

# list solution
res = list(chain.from_iterable(repeat(i, 4) for i in range(1, 5)))

# NumPy solution
arr = np.repeat(np.arange(1, 5), 4)

try this,

range(1,5)*4 # if you don't consider order
sorted(range(1,5)*4) # for ordered seq

With performance updated.

Mihai Alexandru-Ionut Answer:

%timeit [i for i in range(1, 5) for _ in range(4)]

1000000 loops, best of 3: 1.91 µs per loop

jpp answer:

%timeit list(chain.from_iterable(repeat(i, 4) for i in range(1, 5)))

100000 loops, best of 3: 2.12 µs per loop

%timeit np.repeat(np.arange(1, 5), 4)

1000000 loops, best of 3: 1.68 µs per loop

Rory Daulton answer:

%timeit [n for n in range(1,5) for repeat in range(4)]

1000000 loops, best of 3: 1.9 µs per loop

jedwards answer:

%timeit list(i//4 for i in range(1*4, 5*4))

100000 loops, best of 3: 2.47 µs per loop

RoadRunner Suggested in comment section:

%timeit for i in range(1, 5): lst.extend([i] * 4)

1000000 loops, best of 3: 1.46 µs per loop

My answer:

%timeit sorted(range(1,5)*4)

1000000 loops, best of 3: 1.3 µs per loop