I have a list
in Python:
l = ['a', 'c', 'e', 'b']
I want to duplicate each element immediately next to the original.
ll = ['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
The order of the elements should be preserved.
What are duplicates in a list? If an integer or string or any items in a list are repeated more than one time, they are duplicates.
Using the copy() method The Python List copy() is an inbuilt method copy used to copy all the elements from one list to another.
>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With