3
votes

I want to merge 3 lists in to a single list. For example, I have three lists:

a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]

and finally I want to get

merged = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

out of a, b, c

Are there any faster way to merge these 3 lists? Here's my code:

merged = []
a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]
for i in range(0, len(a)):
    merged.append(a[i])
    merged.append(b[i])
    merged.append(c[i])
4

4 Answers

8
votes
import itertools as it

list(it.chain.from_iterable(it.izip(a,b,c)))
2
votes
a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]
d=[]
print [j  for i in zip(a,b,c) for j in i]

Output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

1
votes

Using reduce is another option:

>>> a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]
>>> reduce(lambda x, y: list(x)+list(y), zip(a,b, c))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
0
votes

You can do it like this:

a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]
merged=a+b+c
merged.sort()

Since you are adding the list the merged list will contains all values from abc but not in the correct order.That's why I used .sort() to sort the list