What is the pythonic way of doing the following:
I have two lists a
and b
of the same length n
, and I want to form the list
c = [a[0], b[0], a[1], b[1], ..., a[n-1], b[n-1]]
c = [item for pair in zip(a, b) for item in pair]
Read documentation about zip.
For comparison with Ignacio's answer see this question: How do I convert a tuple of tuples to a one-dimensional list using list comprehension?
c = list(itertools.chain.from_iterable(itertools.izip(a, b)))
c = [item for t in zip(a,b) for item in t]
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