How do I merge two lists into a single list?

I have

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

I want

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

[j for i in zip(a,b) for j in i]

Method 2

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

Method 3

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 )

Method 4

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

Method 5

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

Method 6

Simple.. please follow this pattern.

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

z =list(zip(x,y))
print(z)

Method 7

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()

Method 8

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

Method 9

c = []
c.extend(a)
c.extend(b)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x