Having this:
a = 12
b = [1, 2, 3]
What is the most pythonic way to convert it into this?:
[12, 1, 12, 2, 12, 3]
Having this:
a = 12
b = [1, 2, 3]
What is the most pythonic way to convert it into this?:
[12, 1, 12, 2, 12, 3]
If you want to alternate between a
and elements of b
. You can use itertools.cycle
and zip
, Example -
>>> a = 12
>>> b = [1, 2, 3]
>>> from itertools import cycle
>>> [i for item in zip(cycle([a]),b) for i in item]
[12, 1, 12, 2, 12, 3]
You can use itertools.repeat
to create an iterable with the length of b
then use zip
to put its item alongside the items of a
and at last use chain.from_iterable
function to concatenate the pairs:
>>> from itertools import repeat,chain
>>> list(chain.from_iterable(zip(repeat(a,len(b)),b)))
[12, 1, 12, 2, 12, 3]
Also without itertools
you can use following trick :
>>> it=iter(b)
>>> [next(it) if i%2==0 else a for i in range(len(b)*2)]
[1, 12, 2, 12, 3, 12]
try this:
>>> a
12
>>> b
[1, 2, 3]
>>> reduce(lambda x,y:x+y,[[a] + [x] for x in b])
[12, 1, 12, 2, 12, 3]
import itertools as it
# fillvalue, which is **a** in this case, will be zipped in tuples with,
# elements of b as long as the length of b permits.
# chain.from_iterable will then flatten the tuple list into a single list
list(it.chain.from_iterable(zip_longest([], b, fillvalue=a)))
[12, 1, 12, 2, 12, 3]