2

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]
Yajo
  • 4,116
  • 2
  • 24
  • 33

4 Answers4

4

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]
Anand S Kumar
  • 76,986
  • 16
  • 159
  • 156
  • 1
    Can do it without `itertools` also using `[i for item in zip([a]*len(b),b) for i in item]`. But itertools is a great idea here. – Bhargav Rao Oct 16 '15 at 11:50
1

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]
kasravnd
  • 94,640
  • 16
  • 137
  • 166
1

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]
Hackaholic
  • 15,927
  • 3
  • 44
  • 57
  • All answers are right, but this one is the biest IMHO. Just note that in Python 3 you need to `from functools import reduce` before. – Yajo Oct 21 '15 at 07:11
0
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]
LetzerWille
  • 4,414
  • 2
  • 18
  • 24