4

I want to turn this list:

l=["Three","Four","Five","Six"]

into this one:

['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6]

and I used this code (which works well) to do it:

for i,j in zip(range(1,len(l)*2,2),range(3,7)*2):
    l.insert(i,j)

But I guess Python would not be proud of it. Is there a shorter way for this?

multigoodverse
  • 6,658
  • 15
  • 57
  • 97
  • related: [Pythonic way to combine two lists in an alternating fashion?](http://stackoverflow.com/q/3678869/4279) – jfs Feb 23 '13 at 15:11

2 Answers2

13

I might do something like this:

>>> a = ["Three","Four","Five","Six"]
>>> b = range(3,7)
>>> zip(a,b)
[('Three', 3), ('Four', 4), ('Five', 5), ('Six', 6)]
>>> [term for pair in zip(a,b) for term in pair]
['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6]

or, using itertools.chain:

>>> from itertools import chain
>>> list(chain.from_iterable(zip(a,b)))
['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6]
DSM
  • 319,184
  • 61
  • 566
  • 472
4
In [124]: l=["Three","Four","Five","Six"]

In [125]: [x for x in itertools.chain(*zip(l, range(3,7)))]
Out[125]: ['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6]
avasal
  • 13,666
  • 4
  • 29
  • 47