+2 votes
in Programming Languages by (63.5k points)
I have two lists a= [1,3,5,7,9] and b=[2,4,6,8,10]. I want to merge them and the output list should be [1,2,3,4,5,6,7,8,9,10]. Any pythonic approach?

1 Answer

0 votes
by (271k points)
edited by

You need to use zip() function to create a list of tuples. Those tuples will have elements from list 'a' and 'b'. Then you can use redude() function or Numpy concatenate() function to get the desired output. You can try the following approaches:

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

>>> list(np.concatenate(zip(a,b)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> list(reduce(operator.concat,zip(a,b)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


...