tags:

views:

192

answers:

5

I have

a = [1, 2]
b = ['a', 'b']

I want

c = [1, 'a', 2, 'b']
+7  A: 

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
Mark Byers
+3  A: 
c = a + b

Need 15 characters

Robus
+3  A: 

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']

Nick T
-1 for quadratic time. You can do this in linear time.
Aaron Gallagher
@Aaron Gallagher Fixed, and yet a (subtly) unique answer.
Nick T
+8  A: 
[j for i in zip(a,b) for j in i]
gnibbler
It works, but I can't parse it in my head...
Nick T
[ j for j in i for i in zip(a,b) ] though easier to parse in my head does not work!
sureshvv
Does read weirdly at first :) Mentally chop off everything up to the first `for` and move it to the end, then read that: `for i in zip(a, b)`, `for j in i`, `j`.
shambulator
aaah... neat! thanks.
sureshvv
+1  A: 

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]
John Machin
I'm normally very comfortable with LEs, but this double looping got me all confused. Thanks for the nice explanation.
jeffjose