Reputation: 189
I have two list:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
I need to get something like this:
c = [1, 5, 2, 6, 3, 7, 4, 8]
I use this solution:
c = list(reduce(lambda x, y: x + y, zip(a, b)))
Is there a better way to do this?
Upvotes: 2
Views: 359
Reputation: 213233
Using List Comprehension:
>>> [x for tup in zip(a, b) for x in tup]
[1, 5, 2, 6, 3, 7, 4, 8]
The above nested list comprehension is equivalent to following nested for loops (Just in case you get confused):
result = []
for tup in zip(a, b):
for x in tup:
result.append(x)
Upvotes: 9
Reputation: 142146
Using chain
:
from itertools import chain, izip
interweaved = list(chain.from_iterable(izip(a, b)))
# [1, 5, 2, 6, 3, 7, 4, 8]
Upvotes: 6