List with duplicated values and suffix List with duplicated values and suffix python python

List with duplicated values and suffix


You could make it a generator:

def mygen(lst):    for item in lst:        yield item        yield item + '_ind'>>> a = ['a','b','c']>>> list(mygen(a))['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind']

You could also do it with itertools.product, itertools.starmap or itertools.chain or nested comprehensions but in most cases I would prefer a simple to understand, custom generator-function.


With python3.3, you can also use yield from—generator delegation—to make this elegant solution just a bit more concise:

def mygen(lst):    for item in lst:        yield from (item, item + '_ind')


It can be shortened a little bit by moving the options to the inner for loop in the list comprehension:

a = ['a','b','c'][item for x in a for item in (x, x + '_ind')]# ['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind']


Another alternative with splicing (Python2.x, 3.x):

result = [None] * len(a) * 2result[::2], result[1::2] = a, map(lambda x: x + '_ind', a)result# ['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind']