I have two lists:[a, b, c] [d, e, f]
I want: [a, d, b, e, c, f]
What's a simple way to do this in Python?
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]
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))
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]
You could do something simple using built in functions:
sum(zip(list_a, list_b),())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With