Repeating elements of a list n times

A simpler way to achieve this to multiply the list x with n and sort the resulting list. e.g.

>>> x = [1,2,3,4]
>>> n = 3
>>> a = sorted(x*n)
>>> a
>>> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

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]

You can use list comprehension:

[item for item in x for i in range(n)]

>>> x = [1, 2, 3, 4]
>>> n = 3
>>> new = [item for item in x for i in range(n)]
#[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

The ideal way is probably numpy.repeat:

In [16]:

x1=[1,2,3,4]
In [17]:

np.repeat(x1,3)
Out[17]:
array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])

Tags:

Python