How do I merge two lists into a single list?

Question:

I have

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

I want

c = [1, 'a', 2, 'b']
Asked By: sureshvv

||

Answers:

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
Answered By: Mark Byers

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

Answered By: Nick T
[j for i in zip(a,b) for j in i]
Answered By: John La Rooy

Parsing

[item for pair in zip(a, b) for item in pair]

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 pair in zip(a, b):
    for item in pair :
        temp.append(item )
Answered By: John Machin

An alternate method using index slicing which turns out to be faster and scales better than zip:

def slicezip(a, b):
    result = [0]*(len(a)+len(b))
    result[::2] = a
    result[1::2] = b
    return result

You’ll notice that this only works if len(a) == len(b) but putting conditions to emulate zip will not scale with a or b.

For comparison:

a = range(100)
b = range(100)

%timeit [j for i in zip(a,b) for j in i]
100000 loops, best of 3: 15.4 µs per loop

%timeit list(chain(*zip(a,b)))
100000 loops, best of 3: 11.9 µs per loop

%timeit slicezip(a,b)
100000 loops, best of 3: 2.76 µs per loop
Answered By: SeanM
def main():

drinks = ["Johnnie Walker", "Jose Cuervo", "Jim Beam", "Jack Daniels,"]
booze = [1, 2, 3, 4, 5]
num_drinks = []
x = 0
for i in booze:

    if x < len(drinks):

        num_drinks.append(drinks[x])
        num_drinks.append(booze[x])

        x += 1

    else:

        print(num_drinks)

return

main()

Answered By: Paul Fabing
c = []
c.extend(a)
c.extend(b)
Answered By: Arvind S.P

Here is a standard / self-explaining solution, i hope someone will find it useful:

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

c = []
for x, y in zip(a, b):
    c.append(x)
    c.append(y)

print (c)

output:

['a', '1', 'b', '2', 'c', '3']

Of course, you can change it and do manipulations on the values if needed

Answered By: Samer Aamar

Simple.. please follow this pattern.

x = [1 , 2 , 3]
y = ["a" , "b" , "c"]

z =list(zip(x,y))
print(z)
Answered By: NEETU KUSHWAH
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.