Interleaving Lists in Python [duplicate]
Solution 1:
Here is a pretty straightforward method using a list comprehension:
>>> lists = [['a', 'b', 'c'], ['d', 'e', 'f']]
>>> [x for t in zip(*lists) for x in t]
['a', 'd', 'b', 'e', 'c', 'f']
Or if you had the lists as separate variables (as in other answers):
[x for t in zip(list_a, list_b) for x in t]
Solution 2:
One option is to use a combination of chain.from_iterable()
and zip()
:
# Python 3:
from itertools import chain
list(chain.from_iterable(zip(list_a, list_b)))
# Python 2:
from itertools import chain, izip
list(chain.from_iterable(izip(list_a, list_b)))
Edit: As pointed out by sr2222 in the comments, this does not work
well if the lists have different lengths. In that case, depending on
the desired semantics, you might want to use the (far more general) roundrobin()
function from the recipe
section of the
itertools
documentation:
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
Solution 3:
This one works only in python 2.x, but will work for lists of different lengths:
[y for x in map(None,lis_a,lis_b) for y in x]
Solution 4:
You could do something simple using built in functions:
sum(zip(list_a, list_b),())