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

## Solution:

### Method 1:

For Example-

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

This outputs:

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

This is identical to:

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

Remember that `3*[i]` makes a list with 3 repeated elements (such as `['one', one', 'one']`)

Or You can follw this way

### Method 2:

You can apply itertools to transform a list of list into a list (in a quick 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']``````

Hence, you can identify a function that repeat elements like this :

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

### Method 3:

In case you want to apply pure list comprehension follow below way

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

### Illustration:

In case main list has k elements, repetition factor is n => total number of items in ultimate list: n*k

For mapping range n*k to k elements, Divide by n. Note that integer divison.

### Method 4:

You can attempt to apply `map` with `sum`

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

`This Gives:`

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

### `Method 5:`

In case you intend to use an `itertools` :

``````from itertools import repeat, chain

list(chain.from_iterable(repeat(i, 3) for i in l1))
# ['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']``````

posted Jun 29 in python