Monica Monica - 1 year ago 52
Python Question

Repeating elements in a list

I have a list with elements:

a = ['Monica', 'Mark', 'Nick', 'Margaret']


and I'd like to obtain the following list of names:

['Monica', 'Monica', 'Mark', 'Mark', 'Nick', 'Nick', 'Margaret', 'Margaret']


The simplest solution I came up with is:

lnames = []

for i, j in zip(a,a):
lnames.append(i)
lnames.append(j)


I've also tried to use a comprehension list:

lnames2 = [list(x) for x in zip(a,a)]


but in this case I'm getting:

[['Monica', 'Monica'], ['Mark', 'Mark'], ['Nick', 'Nick'], ['Margaret', 'Margaret']]


and don't know how to get the desire list from that point.

I'd like to ask you what are your solutions for this task.

Answer Source

Try this

def repeat(collection, count):
    for x in collection:
        for i in range(count):
            yield x

a = ['Monica', 'Mark', 'Nick', 'Margaret']

print [x for x in repeat(a, 2)]

prints

['Monica', 'Monica', 'Mark', 'Mark', 'Nick', 'Nick', 'Margaret', 'Margaret']