Repeating elements of a list n times

python

Solution

In case you really want result as list, and generator is not sufficient:

import itertools
lst = range(1,5)
list(itertools.chain.from_iterable(itertools.repeat(x, 3) for x in lst))

Out[8]: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

Problem

How do I repeat each element of a list `n` times and form a new list? For example: ``` x = [1,2,3,4] n = 3 x1 = [1,1,1,2,2,2,3,3,3,4,4,4] ``` `x * n` doesn't work ``` for i in x[i]: x1 = n * x[i] ``` There must be a simple and smart way.

Original source

Related problems