Duplicate elements in a list
import itertools
ll = list(itertools.chain.from_iterable((e, e) for e in l))
At work:
>>> import itertools
>>> l = ['a', 'c', 'e', 'b']
>>> ll = list(itertools.chain.from_iterable((e, e) for e in l))
>>> ll
['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
As Lattyware pointed out, in case you want more than just double the element:
from itertools import chain, repeat
ll = list(chain.from_iterable(repeat(e, 2) for e in l))
Try this
for i in l:
ll.append(i)
ll.append(i)
Demo
It will just do your work but it's not an optimized way of doing this.
use the ans. posted by @Steven Rumbalski
>>> l = ['a', 'c', 'e', 'b']
>>> [x for pair in zip(l,l) for x in pair]
['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
Or
>>> from itertools import repeat
>>> [x for item in l for x in repeat(item, 2)]
['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
This is old but I can't see the straightforward option here (IMO):
[ item for item in l for repetitions in range(2) ]
So for the specific case:
>>> l = ['a', 'c', 'e', 'b']
l = ['a', 'c', 'e', 'b']
>>> [ i for i in l for r in range(2) ]
[ i for i in l for r in range(2) ]
['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
>>>
And generalizing:
[ item for item in l for _ in range(r) ]
Where r is the quantity of repetitions you want.
So this has a O(n.r) space and time complexity, is short, with no dependencies and also idiomatic.