Repeating elements of a list n times

Solution 1:

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])

Solution 2:

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]

Solution 3:

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]

Solution 4:

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]

Solution 5:

A nested list-comp works here:

>>> [i for i in range(10) for _ in xrange(3)]
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9]

Or to use your example:

>>> x = [1, 2, 3, 4]
>>> n = 3
>>> [i for i in x for _ in xrange(n)]
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]