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?
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?
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]])
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]
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)))