-3

I'm working with lists in Python 3.x.

I want to merge two lists:

list1 = [1, 2, 3, 4]
list2 = [7, 8, 9, 19]

Expected output like this:

list3 = [1, 7, 2, 8, 3, 9, 4, 19]

I am not allowed to use any advanced data structures and need to write in a pythonic way.

Amit Yadav
  • 4,422
  • 5
  • 34
  • 79
dealwithit
  • 17
  • 5

5 Answers5

4

Simply we can use list comprehension like this:

list1 = [1, 2, 3, 4]
list2 = [7, 8, 9, 19]

list3 = [v for v1_v2 in zip(list1, list2) for v in v1_v2]

assert list3 == [1, 7, 2, 8, 3, 9, 4, 19]

Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24
2

For example:

from itertools import chain

list(chain(*zip(v1, v2)))
2

zip() the two lists together then flatten with itertools.chain.from_iterable():

>>> from itertools import chain
>>> list1 = [1,2,3,4]
>>> list2 = [7,8,9,19]
>>> list(chain.from_iterable(zip(list1, list2)))
[1, 7, 2, 8, 3, 9, 4, 19]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
0

You can simply use reduce from functools over a sum of the two lists using zip

from functools import reduce
from operator import add

list1 = [1,2,3,4]
list2 = [7,8,9,19]

x = list(reduce(add, zip(list1, list2)))
x
[1, 7, 2, 8, 3, 9, 4, 19]
pissall
  • 7,109
  • 2
  • 25
  • 45
0

Try the below code:

list1 = [1, 2, 3, 4]
list2 = [7, 8, 9, 19]

new_list = []
for i in range(len(list1)):
    new_list.extend([list1[i], list2[i]])
print(new_list)

Output:

[1, 7, 2, 8, 3, 9, 4, 19]
Amit Yadav
  • 4,422
  • 5
  • 34
  • 79