Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate elements in a list

Tags:

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.

like image 935
tesla1060 Avatar asked Feb 14 '13 15:02

tesla1060


People also ask

Can there be duplicate elements in a list?

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.

How do you copy an element in a list Python?

Using the copy() method The Python List copy() is an inbuilt method copy used to copy all the elements from one list to another.


2 Answers

>>> 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']
like image 69
Steven Rumbalski Avatar answered Sep 20 '22 03:09

Steven Rumbalski


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.

like image 21
olivecoder Avatar answered Sep 19 '22 03:09

olivecoder