1

I cannot find a solution to the following problem I have a list of strings, say

base_list = ['d', 'ssa', 'aaa', 'bb']

and I want to repeat this list n times but I need to keep the order of the original list. For example with n=2 the result should be:

final_list =  ['d', 'd', 'ssa', 'ssa', 'aaa', 'aaa', 'bb', 'bb']

EDIT: Not sure if I should mark this question as duplicate or not, since it is in my opinion more generic than the possible duplicate Duplicate element in python list

Community
  • 1
  • 1
MMCM_
  • 617
  • 5
  • 18
  • 3
    http://stackoverflow.com/questions/14878538/duplicate-element-in-python-list – Maroun Aug 05 '15 at 07:55
  • That solves it, despite that the original question asked for duplicates and not the case where `n` is arbitrary. Probably why I have not found the question in first place. – MMCM_ Aug 05 '15 at 08:08

5 Answers5

3
>>> base_list = ['d', 'ssa', 'aaa', 'bb']
>>> n = 2
>>> [i for i in base_list for _ in xrange(n)]
['d', 'd', 'ssa', 'ssa', 'aaa', 'aaa', 'bb', 'bb']

Inside list comprehension you iterate through range with n length (inside loop) and through original list with outer one.

Slam
  • 8,112
  • 1
  • 36
  • 44
0

The following should do what you're looking for

>>> base_list = ['d', 'ssa', 'aaa', 'bb']
>>> final_list = []
>>> n = 10
>>> for item in base_list:
...     for i in range(n):
...             final_list.append(item)
... 
>>> final_list
['d', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'ssa', 'ssa', 'ssa', 'ssa', 'ssa', 'ssa', 'ssa', 'ssa', 'ssa', 'ssa', 'aaa', 'aaa', 'aaa', 'aaa', 'aaa', 'aaa', 'aaa', 'aaa', 'aaa', 'aaa', 'bb', 'bb', 'bb', 'bb', 'bb', 'bb', 'bb', 'bb', 'bb', 'bb']
Joe Young
  • 5,749
  • 3
  • 28
  • 27
0

It is already explained here.

Applied to your code:

>>> base_list = ['d', 'ssa', 'aaa', 'bb']
>>> from itertools import repeat
>>> final_list = [x for item in base_list for x in repeat(item, 2)]
>>> final_list
['d', 'd', 'ssa', 'ssa', 'aaa', 'aaa', 'bb', 'bb']
Community
  • 1
  • 1
ezcoding
  • 2,974
  • 3
  • 23
  • 32
0

I guess one answer from the tagged question (where n=2) also applies to the more generic case:

from itertools import chain, repeat

final_list = list(chain.from_iterable(repeat(item, n) for item in base_list))
MMCM_
  • 617
  • 5
  • 18
0

My first thought was to zip it with itself, then flatten:

import itertools
base_list = ['d', 'ssa', 'aaa', 'bb']
n = 2
list(itertools.chain.from_iterable(zip(*[base_list] * n)))
o11c
  • 15,265
  • 4
  • 50
  • 75