Python: expand list of strings by adding n elements for each original element

You can use itertools to transform a list of list into a list (in a fast way) :

from itertools import chain
l1 = ['one','two','third']
l2 = list(chain.from_iterable([[e]*3 for e in l1]))
# l2 = ['one','one','one','two','two','two','three','three','three']

so you can define a function that repeat elements like this :

def repeat_elements(l, n)
    return list(chain.from_iterable([[e]*n for e in l]))

 l2 = [j for i in l1  for j in 3*[i]]

This gives:

 ['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']

This is equivalent to:

l2 = []
for i in l1:
    for j in 3*[i]:
       l2.append(j)

Note that 3*[i] creates a list with 3 repeated elements (e.g. ['one', one', 'one'])


If you want to use pure list comprehension

 [myList[i//n] for i in range(n*len(myList))]

Explanation:

if original list has k elements, repetition factor is n => total number of items in final list: n*k

To map range n*k to k elements, Divide by n. Remember integer divison


You can try to use map with sum

print(list(sum(map(lambda x: [x] * 3, l1), [])))

Output

['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']