I have
a = [1, 2]
b = ['a', 'b']
I want
c = [1, 'a', 2, 'b']
I have
a = [1, 2]
b = ['a', 'b']
I want
c = [1, 'a', 2, 'b']
If the order of the elements much match the order in your example then you can use a combination of zip and chain:
from itertools import chain
c = list(chain(*zip(a,b)))
If you don't care about the order of the elements in your result then there's a simpler way:
c = a + b
If you care about order:
#import operator
import itertools
a = [1,2]
b = ['a','b']
#c = list(reduce(operator.add,zip(a,b))) # slow.
c = list(itertools.chain.from_iterable(zip(a,b))) # better.
print c
gives [1, 'a', 2, 'b']
Parsing
[j for i in zip(a,b) for j in i]
in your head is easy enough if you recall that the for
and if
clauses are done in order, followed a final append of the result:
temp = []
for i in zip(a, b):
for j in i:
temp.append(j)
and would be easier had it have been written with more meaningful variable names:
[item for pair in zip(a, b) for item in pair]