Create list of single item repeated N times

Viewed 824359

I want to create a series of lists, all of varying lengths. Each list will contain the same element e, repeated n times (where n = length of the list).

How do I create the lists, without using a list comprehension [e for number in xrange(n)] for each list?

9 Answers

If you are looking for a simple repeat like:

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

simply use:

[1, 2, 3] * 3

But if you are seeking for:

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

This one is better while takes more time:

numpy.concatenate([([i]*3) for i in [1,2,3]], axis=0)

Sorry for my really late answer You can use numpy.repeat easily. Just by writing the value that you would like to produce and the number of repetition.

import numpy as np
x = [1,2,3]
y = np.linspace(0,1000,10000)
for i in x:
    new_x = np.repeat(i,len(y))
    print(new_x)

If you're seeking

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

without numpy, you can use the builtin itertools module

from itertools import chain
list(chain.from_iterable(zip(*[[1,2,3]]*3)))

With a simple list comprehension (without even itertools)

[e for x in zip(*[[1,2,3]]*3) for e in x]
Related