Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonically inserting multiple values to a list

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?

like image 276
multigoodverse Avatar asked Dec 03 '22 00:12

multigoodverse


2 Answers

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]
like image 51
DSM Avatar answered Dec 09 '22 15:12

DSM


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]
like image 29
avasal Avatar answered Dec 09 '22 14:12

avasal