1

I have a question:

I have 2 lists:

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

And I want to merge them in order to have the following result:

mergedlist = [1, 4, 2, 5, 3, 6]

How can I do that?

Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71
Dima Kozar
  • 23
  • 3

3 Answers3

2

Like this:

mergedlist = list_1 + list_2

If you want that specific order in mergedlist:

mergedlist = []
for i, entry in enumerate(list_1):
    mergedlist.extend([entry, list_2[i]])
rodgdor
  • 2,530
  • 1
  • 19
  • 26
0

You can use chain from iter tools:

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

from itertools import chain

res = list(chain.from_iterable((list_1[x], list_2[x]) for x in range(len(list_1))))

=> [1, 4, 2, 5, 3, 6]

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
0

In my opinion, the most Pythonic way would be:

merged_list = [item for pair in zip(list_1, list_2) for item in pair]

Alternatively, you can use collections.chain as well:

merged_list = list(chain.from_iterable(zip(list_1, list_2)))

Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71