I'd like to make the python's list to ['a','a','b',b','c','c'] from ['a','b','c'].
Anyboday know to do this? Thank you !
For something that more or less says “I want to repeat each element twice”, there’s the nested list comprehension with range
:
>>> l = ['a', 'b', 'c']
>>> [x for x in l for _ in range(2)]
['a', 'a', 'b', 'b', 'c', 'c']
You can make it a tiny bit shorter with a list multiplication if you find that more readable and won’t need to extend 2
to a large number and convert the list comprehension to a generator expression:
>>> l = ['a', 'b', 'c']
>>> [y for x in l for y in [x, x]]
If you’re a fan of Haskell, where l >>= replicate 2
would work, you can imitate that:
import itertools
from functools import partial
from operator import mul
def flat_map(iterable, f):
return itertools.chain.from_iterable(map(f, iterable))
l = ['a', 'b', 'c']
flat_map(l, partial(mul, 2))
You could always create a new list:
for x in oldList:
newList.append(x)
newList.append(x)
Note that this will create a new list rather than modifying the old one!
source = ['a','b','c']
result = [el for el in source for _ in (1, 2)]
print(result)
gives you
['a', 'a', 'b', 'b', 'c', 'c']