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.
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']
Here's a working example: import itertools a = ['Monica', 'Mark', 'Nick', 'Margaret'] num_repeats = 2 lnames2 = list(itertools.chain(*[[x] * num_repeats for x in a])) print(lnames2)
Encoding issue for Python tool Unidecode on CL
Accept only numbers on a python string [closed]
scrapy spider pass parameters
sending data to particular client from twisted server
Type Error, object cannot be interpreted as an index with tk message box bind commands
What is this condition testing? [duplicate]
Testing Flask login and authentication?
Pyjnius import jar file
Regex - Combining an 'or' with a 'look-behind'
Command fails in python, but not in terminal
Does ndb.toplevel break transactions?
Unique variables names for results in a nested loop
Get unique set of adjacent vertices in python bulbs or gremlin?
Django admin project distribution and management
Increase event handling speed in Twisted?
thread and exception safe way of using HDFStore files